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

Grab values from elements on button click React/Js

I am trying to grab the values from the elements I am mapping through here:

  {userInfo.children &&
    userInfo.children.map((child, key) => {
      const { name, dob, gender } = child;
      return (
        <div key={key}>
          <h3>{name}</h3>
          <h3>{dob}</h3>
          <h3>{gender}</h3>

          <button onClick={removeChild}>Remove</button>
        </div>
      );
    })}

This is my function:

const removeChild = (e) => {
  console.log(e.target.parentNode); };

This is what it looks like

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

So when I click on the button I want to grab the name, dob, and gender of the one being clicked.

The only way I know how to do it is with event.target.parentNode.firstChild but I know this isn’t good practice since if I were to add another element before <h3>{name}</h3> it’ll mess everything up.

I also don’t think I could grab it by className or id. I’ve tried it but it gives me an array of all the data instead of the one clicked on.

Please let me know if I need more details or if this is repeated.

>Solution :

You can pass the child object to the remove child method to do that.

<button onClick={(e) => removeChild(e, child)}>Remove</button>
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