React removing an element when onClick
Little confused about how the whole app works, but I will try to help you.
To make react changes to the dom, you have to put players
in the state
. So, in the removePlayer
you make a copy of this.state.players
in a local variable (just to not change the array directly in state
, it's a good practice), then you make the split in this local variable and finally you setState({ players: localPlayers})
.
This way the "div" will be removed.
We sorted it out in chat. Like expected, it was a problem with the state.
I made a small semi-pseudo snippet with comments as explanation:
import React, { Component } from 'react';
// Your player constant, outside the scope of any React component
// This pretty much just lives in your browser as a plain object.
const players = [
{
name: 'Jabba',
score: 10,
id: 11
},
{
name: 'Han',
score: 10,
id: 1
},
{
name: 'Rey',
score: 30,
id: 10
}
];
class App extends Component {
constructor() {
super();
this.state = {
players, // ES6 Syntax, same as players: players
// Add all your other stuff here
};
}
removePlayer(id) {
const newState = this.state;
const index = newState.players.findIndex(a => a.id === id);
if (index === -1) return;
newState.players.splice(index, 1);
this.setState(newState); // This will update the state and trigger a rerender of the components
}
render() {
const listPlayers = this.state.players.map(player => { // Note the this.state, this is important for React to see changes in the data and thus rerender the Component
<Counter
..
removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
/>
});
return (
<div>
{listPlayers}
</div>
);
}
}
//////////////////////////////////////// Child component
....
<DeleteButton onClick={() => this.props.removePlayer(this.props.player.id)}>
....
Here is how i solved this
i've added an id to the element and then with function remove i detroyed it
const closenotif = () => document.getElementById("notif").remove()
<div id="notif">
<button onClick={destroy}> close </button>
</div>
NB : the element is destroyed in the current document so in the current render
on Next JS this works perfectly
if you are using a live rendering with react this probably won't work
i'll suggest you to work with states in that case