My requirement is to prompt certain radio button based on the amount of array for example. If there are 5 item in an array then it will prompt 5 radio button based on the array’s productName field.
This is my test data:
const testData = [
{
"itemCode": "1",
"productName": "P1 Item name",
},
{
"itemCode": "2",
"productName": "P1 Item name",
}
Then it my radio button:
<div className={styles.selection}>
{testData.productName.map((selection, index) => (
<div onClick={() => handleChangeFlavour(index)} key={index}>
{console.log('EXAMPLE: ', testData)}
{selectedFlavour === index && <img src={RadioSelected.default} />}
{selectedFlavour !== index && <img src={RadioDeselected.default} />}
<span>{selection}</span>
</div>
))
}
</div>
This method return error:
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
The reason why do i put testData.productName is because if i dont it will return this error
react-dom.development.js:13413 Uncaught Error: Objects are not valid as a React child (found: object with keys {itemCode, productName}). If you meant to render a collection of children,
>Solution :
Here’s your problem:
testData.productName.map((selection, index) =>
testData is a array which doesn’t have productName. If you would like to iterate through testData you should do this:
testData.map((selection, index) =>
And, instead of
<span>{selection}</span>
use:
<span>{selection.productName}</span>