'straight out of react.js.org and it crashes

export default function NumberList(props) {
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")
);

It works ,but when i reload it breaks , it says "Uncaught TypeError: Cannot read properties of undefined (reading 'map')"



Solution 1:[1]

export default function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers?.length ? 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")
);

Hi, you can use ternary operator to check if array not undefined and has length. With this way you can prevent undefined error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaan Bayram