Want to delete item from list in ReactJS? You are managing the data in Parent component and rendering the UI in Child component, so to delete item from child component you need to pass a function along with data, call that function from child and pass any unique identifier of list item, inside parent component delete the item using that unique identifier.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class App extends React.Component{ constructor(){ super(); this.state = { data: [1,2,3,4,5] } this.delete = this.delete.bind(this); } delete(id){ this.setState(prevState => ({ data: prevState.data.filter(el => el != id ) })); } render(){ return( <Child delete={this.delete} data={this.state.data}/> ); } } class Child extends React.Component{ delete(id){ this.props.delete(id); } render(){ return( <div> { this.props.data.map(el=> <p onClick={this.delete.bind(this, el)}>{el}</p> ) } </div> ) } } ReactDOM.render(<App/>, document.getElementById('app')) |
1 2 3 4 |
<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> <div id='app'/> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.