Matt Saunders
Matt Saunders

Reputation: 4371

React undefined props issue

I'm passing a props object to a child component. The problem I'm having is that sometimes some of the nested values will be null, or undefined, and therefore I'm getting the dreaded props undefined message Uncaught TypeError: Cannot read property 'xxx' of undefined.

As I understand defaultProps is only triggered when the props object is null, not when only some of its values are null.

Example:

this.state {
    person: { 
        name: "Matt", 
        age: 34, 
        OtherDetails: { city:"", country: "" } 
    }
}

In the example above sometimes the city or country values will be null or undefined. Checking for these instances seems very difficult and laborious - what is the best way to deal with situations like this when props data is partial and unreliable?

Upvotes: 1

Views: 1161

Answers (1)

Andrew Rosewarn
Andrew Rosewarn

Reputation: 111

If as your question suggests you are just trying to pass an object as a prop, and then access properties of that object in your component that may not exist then have you considered providing default values? (This assumes your using ES6 syntax).

I would use destructuring in the render method to access each property I am going to use in the render method, and for each item provide a default value as below.

class PersonComp extends React.Component {
    render() {
        const {
            name = '',
            age = 0,
            OtherDetails: {city = ''},
            OtherDetails: {country = ''}

        } = this.props.person;

        return (
            <div>
                <div>{name}</div>
                <div>{age}</div> 
                <div>{city}</div>
                <div>{country}</div>
            </div>

        )
    }
}

By doing this should city or country not exist in the data provided then they will be created and assigned the value of empty string.

Upvotes: 3

Related Questions