0

I have a component that I want to use as a template and it can be passed various values. However, if and when that value doesn't exist, the component returns Cannot read value of undefined.

The component:

const Component = ({ value }) => (
   <div>
      <p>{!value ? '' : value}</p>
   </div>
)

And then rendering the template with different values...

<Component value={object1.value} />
<Component value={object2.value} /> // object2 doesn't exist, so error thrown

How to I get the component to render null, (or something else) if the props it receives don't exist? Or is there a better solution?

Paulos3000
  • 3,355
  • 10
  • 35
  • 68
  • You can give it a default value, no? – Dave Newton Jan 23 '17 at 19:35
  • @DaveNewton How do you do that in this context? – Paulos3000 Jan 23 '17 at 19:36
  • http://stackoverflow.com/questions/26578167/es6-object-destructuring-default-parameters – Dave Newton Jan 23 '17 at 19:39
  • So by "does not exist" you mean `object2` is not declared at all? – Fabian Schultz Jan 23 '17 at 20:03
  • @FabianSchultz - Yes I do. I was hoping that I could use a ternary operator to signify if that value has not been declared to assign the value to `null` or something else. But I guess that's not possible right? – Paulos3000 Jan 23 '17 at 20:28
  • [No, not possible](http://stackoverflow.com/a/31043520/6941627). You could do something like this `` but it's not pretty. Why do you need that behaviour anyways, how are these object names generated? – Fabian Schultz Jan 23 '17 at 21:12
  • Aaaah, long story :) Trying to catch all responses of an unpredictable API. It's forcing me to account for some fringe cases that are screwing up my logic. Fun times :/ – Paulos3000 Jan 23 '17 at 21:29

1 Answers1

1

From how you have posed the question, <Component isn't the issue its the fact you are trying to access a property on an undefined value I.E. object2 was never defined so when you try to do a property access on it you get a javascript reference error. There isn't much context to go off of but with what you provided you could do :

<Component value={object2 ? object2.value : null} />

Ideally you would be making sure object1, object2, etc are at least instantiated as an empty object and can replace them with actual values that way instead of getting a javascript reference error you would just have undefined returned when the property lookup takes place

finalfreq
  • 6,830
  • 2
  • 27
  • 28
  • No problem! Personally I use Lodash's `_.get` function which is great if you are already using Lodash or plan on using it. It just takes object as first argument and then the key path as the second argument `_.get(object2, 'value')` and if object2 was undefined it just returns undefined – finalfreq Jan 24 '17 at 16:36