Dodz
Dodz

Reputation: 307

Render undefined in react component?

Why react crashes when it access props of undefined cannot read property of undefined

ex One: Knowing that props.name is undefined this code will return an error.

const component = (props) => {
         return(
             <p>{props.name}</p>
     )
  }

ex Two: Why in this case it is ok for react to render without errors undefined which in this case would return invisible.

const componentTwo = () => {
         return(
             <p>{undefined}</p>
     )
  }

Upvotes: 3

Views: 14425

Answers (2)

Drew Wilken
Drew Wilken

Reputation: 107

If you are not passing props to the component, then props will be undefined. If this is true (that you are passing no props), then trying to access props.name will throw that exact error! In order to ensure that props are given to the component, you can do as the other answer says, using the && operator.

const MyComponent = props => {
  return <p>{props && props.name}</p>;
};

To answer the other part, React will render {undefined} because there is nothing to render. Just saying undefined isn't trying to access a property of undefined. Similar to if you had an object like

var myObject = undefined

and then tried to access a name property of this object:

console.log(myObject.name) //throws 'can not read property name of undefined'

Upvotes: 1

Tholle
Tholle

Reputation: 112787

Writing props.name should not give you the error cannot read property 'name' of undefined. If the name property doesn't exist on the props object, props.name will just be undefined.

However, if there is e.g. no person property on the props object, props.person will give you undefined. Trying to access name on undefined will then give rise to your error, because you can't access a property on undefined.

You could then use the && operator to make sure props.person is set before using props.person.name.

Example

const MyComponent = props => {
  return <p>{props.person && props.person.name}</p>;
};

Also make sure that your component names start with an uppercase letter, or the component will be interpreted as a string instead of as a variable when using it.

Upvotes: 8

Related Questions