Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prompt radio button based on usestate

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading