Thursday, November 28, 2019

[ReactJS][Resolved] ReferenceError: props is not defined

Error Message


Source Code

class NumberList extends React.Component{
  render(){
    const numbers = props.numbers;
    const listItems = numbers.map((number) =>
      <li key={number.toString()}>
        {number}
      </li>
    );
    return (
      <ul>{listItems}</ul>
    );
  }
}
const numbers = [1,2,3,4,5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
The variable "props" highlighted in yellow is not defined in the class and render method, you can define a variable named "props" within render method but in this case, we should add a "this" and dot notation in front of it.

Correction

class NumberList extends React.Component{
  render(){
    const numbers = this.props.numbers;
    const listItems = numbers.map((number) =>
      <li key={number.toString()}>
        {number}
      </li>
    );
    return (
      <ul>{listItems}</ul>
    );
  }
}
const numbers = [1,2,3,4,5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

No comments :

Post a Comment