Home > Software engineering >  Remove item from array react js
Remove item from array react js

Time:01-08

I'm having trouble with removing an object from an array. I have tried many options and nothing works. Please help me solve this problem.

Thanks for your help

My array:

export const SavedList = [
    {
      word: 'hello',
      translate: 'привет',
      note: 'say say'
    }
]

Remove callback (deletePost)

class Menu extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el)=> el.id !== id)
    })
  }
  render() {
    return (
          <div className="content">
            <Routes>
              <Route path="/" element={<Layout />}>
                  <Route path="saved" element={<Saved data={this.state.data} del={this.deletePost}/>}/>
              </Route>
            </Routes>
            <div>
            </div>
        </div>
    );
  }
}
export default Menu;

here button delete with onClick

class Saved extends Component {
  render() {
    const sl = this.props.data.map((sl, id) => {
      return (
        <div className="saved-card" key={id}>
          <div className="content">
            <p>{id}</p>
            <p>{sl.word}</p>
            <p>{sl.translate}</p>
            <p>{sl.note}</p>
          </div>
          <div className="btn-block">
            <button
              onClick={() => this.props.del(id)}
              type="button"
              className="delete-btn"
            >
              delete
            </button>
          </div>
        </div>
      );
    });
    return (
      <div>
        <h2>Saved list</h2>
        <div className="saved-inner">
          <div className="saved-list">{sl}</div>
        </div>
      </div>
    );
  }
}

export default Saved;

CodePudding user response:

This issue is because el.id doesn't have any value in delete Post Function. That function also needs to have an ID variable, I have named it as i_di.

class App extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el, i_di)=> i_di !== id )
    })
  }
  render() {
    return (
          <div className="content">
              {<Saved data={this.state.data} del={this.deletePost}/>}
            
        </div>
    );
  }
}
export default App;

  • Related