0

I am new to React and was trying to list all the array numbers. From the tutorial what I have understood is functions are also components in react. I tried to create a function component and access that functional component in another component(PersonList) But while executing I got the below error.

ReferenceError: number is not defined[Learn More]

If I replace PersonList with NumberList, it works fine. Can you please let me know what is wrong with my code?

Working code =============

ReactDOM.render(
    <NumberList />,
    document.getElementById('root')
);

Not working code ================

class PersonList extends React.Component {

    render() {
        <div>
            <NumberList/>
        </div>
    };
}

function NumberList() {
    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
        <li>{number}</li>
    );
    return (
        <ul>{listItems}</ul>
    );
}



ReactDOM.render(
    <PersonList />,
    document.getElementById('root')
);

3 Answers 3

1

Change your PersonList component like below:

 class PersonList extends React.Component {

    render() {
      return ( //no return in your component
         <div>
          <NumberList/>
         </div>
      );

    };
}

there's no return in your PersonList .Change it like above and demo

Sign up to request clarification or add additional context in comments.

Comments

1

You're missing a return statement in your render method. The correct code looks like this.

class PersonList extends React.Component {

  render() {

    return(
      <div>
        <NumberList />
      </div>
    )
  };
}

function NumberList() {
  const numbers = [1, 2, 3, 4, 5];
  const listItems = numbers.map((number) =>
    <li>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}


ReactDOM.render(
  <PersonList />,
  document.getElementById('root')
);

Comments

0
function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.