SuspiciousCloud
SuspiciousCloud

Reputation: 13

How should I go about changing the state of siblings when a child is clicked in React?

I'm new to React and I just ran into the problem where I need to select a single component in an array, but when I select that one child component, I want it to change the state/styling of the sibling components.

So let's say I have 3 child components in an array. How can I select one item and style it to look like it's selected, but then deselect/destyle all other siblings?

I have an example project here: https://codesandbox.io/s/summer-river-h20cx?file=/src/Parent.js I want to only have one child item green at a time, when selected.

Thanks!

Upvotes: 1

Views: 174

Answers (2)

Devin Ekadeni
Devin Ekadeni

Reputation: 648

in my opinion it's more efficient to control the selected props from the parent and also passing onClick into the child component and utilize the child component as presentational component.

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedId: 1,
      childArray: [
        {
          id: 1,
          Name: "Child 1"
        },
        {
          id: 2,
          Name: "Child 2"
        },
        {
          id: 3,
          Name: "Child 3"
        }
      ]
    };
    this.handleClickChild = this.handleClickChild.bind(this);
  }

  handleClickChild(id) {
    this.setState({ selectedId: id });
  }

  render() {
    var childObjects = this.state.childArray.map(item => (
      <Child
        text={item.Name}
        selected={item.id === this.state.selectedId}
        onClick={() => this.handleClickChild(item.id)}
      />
    ));

    return <div className="parent">{childObjects}</div>;
  }
}

you can see this codesandbox that I've made based on yours https://codesandbox.io/s/crazy-haze-vy75f?file=/src/Parent.js

Upvotes: 1

Alex V
Alex V

Reputation: 216

Try lifting state up: move state to the parent component and let it control it while child components are stateless.

Upvotes: 0

Related Questions