Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  75] [ 3]  / answers: 1 / hits: 39519  / 8 Years ago, sun, october 2, 2016, 12:00:00

How do I remove the item when user clicked x? pass the id to parent and use filter()? In jquery I can just use remove() and that's about it. Very new to react, need guidance.





import React from 'react';

const RenderItem = (props) => {
return(
<ul id=todo>
{props.items.map((item,i) =>
<li className='list-group-item' data-id={item.id} key={i}>{item.name}
<button className=btn btn-sm btn-primary onClick={}>X</button>
</li>
)}
</ul>
)
};

const TodoItems = React.createClass({
getInitialState() {
return {
items: [
{id:1,name:Gym},
{id:2,name:Jump},
{id:3,name:Racing}
],
editing: false
}
},
edit(){
this.setState({editing: true})
},
save(){
this.setState({editing: false})
},
remove(id){
//return this.items.filter((item,i) => item.id !== id)
}
render(){
return(
<RenderItem items={this.state.items} />
)
}
})


ReactDOM.render(
<TodoItems />,
document.getElementById('container')
);

<div id=container>
</div>


<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>





This is my code on fiddle https://jsfiddle.net/3mn105sj/, I don't know why I failed to use react here.


More From » reactjs

 Answers
10

Check the fiddle:


https://jsfiddle.net/zp5oqnsh/1/


const RenderItem = (props) => {
return(
<ul id="todo">
{props.items.map((item,i) =>
<li className='list-group-item' data-id={item.id} key={i}>{item.name}
<button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>
</li>
)}
</ul>
)
};

const TodoItems = React.createClass({
getInitialState() {
return {
items: [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
],
editing: false
}
},
edit(){
this.setState({editing: true})
},
save(){
this.setState({editing: false})
},
remove(id){
this.setState({
items: this.state.items.filter((el) => id !== el.id)
})
//return this.items.filter((item,i) => item.id !== id)
},
render(){
return(
<RenderItem items={this.state.items} remove={this.remove}/>
)
}
})


ReactDOM.render(
<TodoItems />,
document.getElementById('container')
);

Pass the remove() as a props and call the remove() onClick with the id and apply filter..


Hope it helps!


[#60533] Thursday, September 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;