Source:  Twitter logo

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.

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!

6 users liked answer #0dislike answer #06
Pranesh Ravi profile pic
Pranesh Ravi

you need to use react-dom for example;

import { unmountComponentAtNode } from 'react-dom';

onDismiss(node) {
  unmountComponentAtNode(node);
  document.body.removeChild(node);
}
2 users liked answer #1dislike answer #12
Cem Arguvanlı profile pic
Cem Arguvanlı

If you are creating a stateless component and passing props as argument, you can't use 'this.props'

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>
)};
0 users liked answer #2dislike answer #20
Alberto Centelles profile pic
Alberto Centelles

React is all about manipulating state to trigger rerenders of the DOM. Instead of arbitrarily removing the element from the DOM like you would in jQuery, you should update the state by filtering out the item from props.items which will trigger a rerender of the DOM with the item removed. This way, the item will still be removed from the DOM even after any subsequent rerenders - whereas with document.removeChild() or unmountComponentAtNode() the item will reappear after a subsequent rerender (in theory, I haven’t personally tested).

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={() => 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((prev) => {
       ...state,
       items: prev.items.filter((item) => item[id] !== id)
    })
  }
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove} />
    ) 
  }
})


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

If you don’t want the item to be removed from props.items, then add something like an isCompleted key for each item. Update the state by toggling the item’s isCompleted key to true and have the DOM only render the items that isCompleted === false.

import React from 'react';
const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => {
            item.isCompleted === false && (
                <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", isCompleted: false },
        {id:2, name:"Jump", isCompleted: false },
        {id:3, name:"Racing", isCompleted: false }
      ],
      editing: false
    }
  },
  edit(){
    this.setState({editing: true})
  },
  save(){
    this.setState({editing: false})
  },
  remove(id){
    this.setState((prev) => {
       ...state,
       items: prev.items.map(item => (item.id === id ? Object.assign({}, item, { isCompleted: true }) : item))
    })
  }
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove} />
    ) 
  }
})


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

Alternatively, you can store the removed items in a new array.

0 users liked answer #3dislike answer #30
Sharna J profile pic
Sharna J

In MY case I used the useEffect and worked just fine.

Like this:

const [clients, setClient] = useState([]);

useEffect(() =>{getData();},[clients]);

I have a remove function that removes the element in the database, and when the clients array change, the getData is fired and automatically updates the DOM.

0 users liked answer #4dislike answer #40
italofgcoura profile pic
italofgcoura

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).