user16215458
user16215458

Reputation:

How to add a button that deletes an item from the list in react.js

I'm learning React and I'm making an input field that outputs a list I would like, please, how to create a function that clears the list I have entered or deletes a specific item from the list.

let eleValue;
let myItems = [];

let handleChange = (e)=>{
    eleValue = e.target.value;
}

let handleForm = (e)=>{
    e.preventDefault();
    myItems.push(eleValue);
    e.target.elements[0].value = "";
    render()
}

let removeList =()=>{

}

let render = ()=>{
    let ele = (
        <div>
            <form onSubmit={handleForm} action="">
                <input onChange={handleChange} type="text" />
                <input type="submit" />
                <button onClick={removeList}>remove</button>
                <ul>
                {myItems.length? myItems.map((item)=>
                    <li>{item}</li>
                ):''}
            </ul>
            </form>
            
        </div>
    )
    ReactDOM.render(ele, document.getElementById('app'))
}
render();

Upvotes: 0

Views: 900

Answers (1)

Coffezilla
Coffezilla

Reputation: 386

First of all, define the array of content with objects: const myItems = [{id: 1},{id: 2},{id: 3}]

The id is used to check which item you will delete.

After have the array, you can pretty much use filter in javascript to strip the item from the array.

filter in Javascript

// my set of items
const myItems = [
  {id: 1},
  {id: 2},
  {id: 3}
];

// choose the id to delete
const idToDelete = 2;

// new array of items without the item with id 2
const myNewItems = myItems.filter((item) => item.id !== idToDelete);

console.log('old set of items', myItems)
console.log('new set of items', myNewItems )

Upvotes: 1

Related Questions