Ad

How To Render Object That Pass Through Props In ReactJS?

- 1 answer

I am trying to render the data (object) that comes through props. However, I have got the following error:
Uncaught TypeError: Cannot convert undefined or null to object Some how, I do not know why the data or object is null although the state of the data is updated during componentDidMount(). Would you help me why the data is null?

Please look class A to see how the data is consumed

class A extends React.Component {
  state = {
    data: null
  };

  componentDidMount() {
    this.data = this.props.location.state.data;
    this.setState({ data: this.props.location.state.data });
  }

  render() {
    return (
      <div>
        {Object.keys(this.data).map((key, index) => (
          <p key={index}> value is {this.data[key]}</p>
        ))}
        hello
      </div>
    );
  }
}

A.propTypes = {
  data: PropTypes.object,
  location: PropTypes.object
};
export default A;

Assume, this.data contains the data in the following format

{
    id: 1,
    userName: "ABDXY",
    date: "01/12/2020",
    time: "21:00"
}
Ad

Answer

this.data is not defined. You can access the data that is set in the state using this.state.data

Please ensure that this.props.location.state.data is not null

class A extends React.Component {
  state = {
    data: {}
  };

  componentDidMount() {
    // this.data = this.props.location.state.data;  => not required.
    this.setState({
      data: this.props.location.state.data
    });
  }

  render() {
    return ( <
      div > {
        Object.keys(this.state.data).map((key, index) => ( < 
          p key = {
            index
          } > value is {
            this.state.data[key]
          } < /p>
        ))
      }
      hello <
      /div>
    );
  }
}
Ad
source: stackoverflow.com
Ad