Home > Blockchain >  How to enable a button to delete items in an array?
How to enable a button to delete items in an array?

Time:07-11

I have a task that needs me to create a button that deletes certain items in an array. I have passed an array as a prop to the child component (). Now in the child component, whenever I click the delete button, it doesn't seem to work and I am struggling to find the problem.

Here's the link to the code: (App.js)

function App() {
  const [input, setInput] = useState("");
  const [list, setList] = useState([]);
  
  const handleSubmit = (e) => {
      e.preventDefault();
      setList([...list, {val: input, key: Math.floor(Math.random() * 11)}]);
  }

  const handleChange = (e) => {
       setInput(e.target.value)
  }
  return(
    <div className='App'>
     <header className='App-header'>
       <div className='Wrapper'>
         <div className='input-container'>
         <input type="text" onChange={handleChange} value={input} />
         <input type="submit" onClick={handleSubmit} />
         </div>
       <List list={list}/>
       </div>
     </header>
    </div>
  )
}


export default App;

And the link to the "" component that:

function List(props) {
    //handle delete. we return elements on a condition that the keys do not match
    const handleDelete = (key)=>{
        props.list.filter((items)=>{
            return items.key != key
        })
    }


  return (
      <>
          {
              props.list.map(function(listItem){
                  return (
                      <div className='lists' key={listItem.key}>
                          <p>{listItem.val}  <button onClick={handleDelete(listItem.key)}>Delete</button> </p>
                      </div>
                  )
              })
          }
      </>
  )
}

export default List

CodePudding user response:

You need to pass setList to List component

<List list={list} setList={setList}/>

List

const handleDelete = (key)=>{
    const newList = props.list.filter((items)=>{
        return items.key != key
    })
    props.setList(newList)
}

CodePudding user response:

The filter function is returning a new array, it is not modifying the existing array you have. Therefore, you have to assign the newly filtered list using the setList function. You can either pass the setList function as a prop to your child component to call it after filtering, or provide your child component a handleDelete callback function which you would define in the parent component (which will do the filtering and setting in the parent) via a prop, and then you just call it in the child component on click.

  • Related