user414967
user414967

Reputation: 5335

React js component is not rendering

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')
);

Upvotes: 0

Views: 65

Answers (3)

Dhavalkumar Prajapati
Dhavalkumar Prajapati

Reputation: 131

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')
);

Upvotes: 0

Oscar W
Oscar W

Reputation: 484

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')
);

Upvotes: 1

Jayavel
Jayavel

Reputation: 3407

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

Upvotes: 1

Related Questions