1

I have an array in firebase with root branch named Rooms and a state in the app named rooms (array). I was able to make it so when user enter new room name and press submit, it is being added to the end of Rooms object.

screenshot of firebase database

I wanted to implement a delete method so when user clicks on x button next to room name, it will delete that element from the state and from firebase, but I have no success implementing it.

My starting point is a thread from SO similarly titled. I fail to implement the code on the <li> component that works. This is what I have:

Chatroom.js

  handleRemove(index) {
    var array =  this.state.rooms.slice();
    array.splice(index, 1);
    this.setState({
      rooms: array
    })
  }
  ...
  render(){
    <div><DisplayChatrooms rooms={this.state.rooms} handleRemove={this.handleRemove.bind(this)} /></div>

DisplayChatrooms.js

class DisplayChatrooms extends React.Component{
  render(){
    console.log('handleRemove: ', this.props.handleRemove); //this prints out the handleRemove function just fine
    var rooms = this.props.rooms.map(function(room, index){
      return (
        <li key={index}>{room} <a href="#">x</a></li>
      )
    })
    return(
      <div>
        <ul>
          {rooms}
        </ul>
      </div>

When I modified the li to include handleRemove, it shows this error: Uncaught TypeError: Cannot read property 'props' of undefined.

<li key={index}>{room} <a href="#" onClick={this.props.handleRemove}>x</a></li>

How can I implement a method that allows user to remove that element when x is clicked?

Community
  • 1
  • 1
Iggy
  • 5,129
  • 12
  • 53
  • 87

1 Answers1

1
 this.props.rooms.map(function(room, index){
  return (
    <li key={index}>{room} <a href="#">x</a></li>
  )
})

the "li" is in the scope of function(room, index), that the this is point to global in this case window object, thats why props is not on this, you can use es6 fat arrow

this.props.rooms.map((room, index) => {})

or old school method

var self = this;
this.props.rooms.map(function() { self.props.handleRemove })
Sean
  • 2,990
  • 1
  • 21
  • 31