Thian Kian Phin Thian Kian Phin - 2 months ago 16
React JSX Question

Remove DOM in react.js,

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.

Answer

Check the fiddle:

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

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

Hope it helps!

Comments