Search code examples
reactjsreact-props

React in render method cant read this.props.location.state"


I learn React and now I cant figure out how to do this I get:

Cannot read property 'state' of undefined

on the line:

  if (album.route === this.props.location.state.week) {

This is the render:

 render() {
        
    let photosArr = []
    albums.map((album) => {
      if (album.route === this.props.location.state.week) {
        album.data.forEach((photo) => {
          photosArr.push([photo.id, photo.src])
        })
      }
    })
    this.state.items = photosArr
    console.log(this.props.location)

I'm calling it like this using import { withRouter } from "react-router";:

onImageClick = val => {
    const {history} = this.props;
    history.push("/timeLineViewer", val);
  };

And it works if I remove the albums.map((album.. code then the console.log.... show the props vale

The problem is that the rendered gets called before I make the call to updated the props from onImageClick so I get the above error if I have the this.props.location.state.week..

How can I handle this since this.props.location.state don't exist before I call onImageClick


Solution

  • How can I handle this since this.props.location.state don't exist before I call onImageClick

    Javascript throws an error since you are trying to get a property of undefined. So you should handle the undefined case.

    Replace:

    if (album.route === this.props.location.state.week) 
    

    with:

    if (album.route === this.props.location?.state?.week) 
    

    Or :

    if (this.props.location &&
        this.props.location.state &&
        album.route === this.props.location.state.week)