Pratish Shrestha
Pratish Shrestha

Reputation: 1902

Handling "cannot read property of null" error

I have a projects object like so

projects: {
   projectType: {id: 1, title:'something'},
   budgetType: {id: 1, title:'something'},
   projectStatus: {id: 1, title: 'something'}
}

and im rendering this in the render method.

<td>{this.props.projects.projectType.title}</td>
<td>{this.props.projects.budgetType.title}</td>
<td>{this.props.projects.projectStatus.title}</td>

This works fine, but sometimes the server sends in null when that object is not present as it is not a required field to be entered. So, this throws a "cannot read property of null error". I was using a ternary operator in each case to solve this error which doesnt look really nice. Is there any better way to solve this?

<td>{(this.props.projects.projectType.title)?this.props.projects.projectType.title: ''}</td>

EDIT: I have a "ProjectList" component which lists all the project rows like so

//in render
<tbody>
    {Object.keys(this.props.projects).map(this.renderProject)}
</tbody> 

//renderProject Function
<Project key={key} project={this.props.projects[key]}/>

Upvotes: 0

Views: 2155

Answers (2)

sabithpocker
sabithpocker

Reputation: 15566

When accessing properties of null Javascript will throw this error. One usual pattern we use is like:

this.props.projects.projectType && this.props.projects.projectType.title

Here the second expression is evaluated only if first one is true. null and undefined are false so the second one won't be evaluated, an no error thrown.

This is because false && <whatever> === false

If projectType is not null, the value of the expression will be equal to the last item in the chain.

This can be chained in fancy ways like:

this && this.props && this.props.projects && this.props.project.projectType;

But it is always recommended to keep these checks inside the javascript file and use some derived attribute for the view.


I don't know if ampersand is a valid token in react expressions. Please refer to other answers on how such cases are handled in React way.

Upvotes: 2

John Mc
John Mc

Reputation: 2933

Why not create a simple helper method which accepts the property and returns either the value or an empty string if its null? You would still do the ternary operator but only in one place

Upvotes: 0

Related Questions