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

React Js child map function returns only first parent map function value but not others on using input type radio

I am using 2 arrays and rendering it as parent and child map function

Array :

const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},];

const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},];

Now when I render these arrays as parent and child and in onChange function in radio button i get each time "1" as id and I want parent’s id 2 and 3 also on onChange function.

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

export const app = () => {

    const array1 = [{id: 1,message: "apple",},{id: 2,message: "banana",},{id: 3,message: "cherry",},];

    const array2 = [{id: 4,reply: "mango",},{id: 5,reply: "grape",},{id: 6,reply: "kiwi",},];

    const handleChange = (parentId) => {
        console.log(parentId) // Each time returns 1 and not 2 and 3
    }

  return (
    <div>
      {array1.map((parentItem) => {
        return (
          <div key={parentItem.id}>
            <span>{parentItem.message}</span>
            {array2.map((childItem) => {
              return (
                <div key={childItem.id}>
                  <input
                    type="radio"
                    id={childItem.id}
                    value={childItem.reply}
                    onClick={()=>handleChange(parentItem.id)}
                  />
                  <label htmlFor={childItem.id}>{childItem.reply}</label>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
};

>Solution :

The issue is that you have given multiple input elements the same id and each label is linked to the first element of that id in the document. Therefore, clicking on any label will result in checking one of the radio buttons in the first <div> (where parentItem.id is 1).

To rectify this, ensure that your ids are unique across the document.

const id = parentItem.id + '_' + childItem.id;
return (
  <div key={childItem.id}>
    <input
      type="radio"
      id={id}
      value={childItem.reply}
      onClick={() => handleChange(parentItem.id)}
    />
    <label htmlFor={id}>{childItem.reply}</label>
  </div>
);
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