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.
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?