Reputation: 5335
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
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
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