Home > Software design >  Grab values from elements on button click React/Js
Grab values from elements on button click React/Js

Time:03-01

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

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.

CodePudding user response:

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

<button onClick={(e) => removeChild(e, child)}>Remove</button>

CodePudding user response:

I think a better way for you to do this is to make a separate Child component instead of rendering just the html elements. Also you should store the userInfo in some form of state. One of the purposes of React is to avoid having to use direct DOM manipulation and to manage data in a store rather than just in the DOM and then manipulating it that way.

Instead, create a Child component that consists of

<div key={key}>
          <h3>{name}</h3>
          <h3>{dob}</h3>
          <h3>{gender}</h3>

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

Then in this component, you can pass props, even implement state if you want to but you don't have to. You can now pass all of the child data down to the component, as well as removeChild.

{userInfo.children &&
    userInfo.children.map((child, key) => {
      return (
        <Child key={key} child={child} removeChild={removeChild}/>
      );
    })}

Child.js

const Child = ({child, removeChild, key}) =>{
  const {name, dob, gender} = child
  <div key={key}>
    <h3>{name}</h3>
    <h3>{dob}</h3>
    <h3>{gender}</h3>
   <button onClick={()=>removeChild(key)}>Remove</button>
  </div>

}

And in your parent component here is the updated removeChild.

const removeChild = (index) =>{
  var dummy = {...userInfo}
  dummy.children = dummy.children.filter((x, i)=>i!==index)
  //below is where you use hooks or class state or whatnot 
  //to update userInfo to reflect the new children list
}
  • Related