Search code examples
javascriptreactjsecmascript-6

React removing an element when onClick


I am trying to remove a div when onClick is pressed. The div exists on my parent component where I have

 render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
        removePlayer={this.removePlayer}
        handleClick={player}
      />
    ));

    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }

It passes props to the child component where the button to delete the div, here

    return (
      <div
        style={{ display: this.state.displayInfo }}
        className="group-list"
        ref={sortableGroupDecorator}
        id="cell"
      >
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
            <Col>
              <DeleteButton onClick={removePlayer}>
                <Icon name="delete" className="delete-adjust fa-minus-circle" />
              </DeleteButton>
            </Col>

(I snipped the rest of the code because it was long and not useful here)

The array (a separate file) is imported into the Parent component and it reads like this

const players = [
  {
    name: 'Jabba',
    score: 10,
    id: 11
  },
  {
    name: 'Han',
    score: 10,
    id: 1
  },
  {
    name: 'Rey',
    score: 30,
    id: 10
  }
];

export default players;

So what I'm trying to do is write a function on the main parent that when it is clicked inside the child, the div is removed, deleted, gone (whatever the best term is) sort of like "remove player, add player"

On my parent component, I've written a function where the console.log works when it is clicked in the child, but whatever I write in the function doesn't seem to want to work.

The function I'm building (in progress, I'm still a little lost here) is:

  removePlayer() {
    console.log('this was removed');
    players.splice(2, 0, 'Luke', 'Vader');
  }

which is mapped over here as a prop

const listPlayers = players.map(player => (
  <Counter
    key={player.id}
    player={player}
    name={player.name}
    sortableGroupDecorator={this.sortableGroupDecorator}
    decrementCountTotal={this.decrementCountTotal}
    incrementCountTotal={this.incrementCountTotal}
    removePlayer={this.removePlayer}
    handleClick={player}
  />
));

And passed into the child here:

render() {
const {
  name,
  sortableGroupDecorator,
  decrementCountTotal,
  incrementCountTotal,
  removePlayer
} = this.props;

return (
  <div
    style={{ display: this.state.displayInfo }}
    className="group-list"
    ref={sortableGroupDecorator}
    id="cell"
  >
    <CountCell style={{ background: this.state.color }}>
      <Row style={{ alignItems: 'center', marginLeft: '-42px' }}>
        <Col>
          <DeleteButton onClick={removePlayer}>
            <Icon name="delete" className="delete-adjust fa-minus-circle" />
          </DeleteButton>

I know all this is lengthy and I wanted to provide as much detail as I could because React is still new to me and I get confused with some of the verbiages. Thanks for helping out in advance


Solution

  • 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)}>
    
    ....