tmp dev
tmp dev

Reputation: 9219

Redux react inter-component communication

I have the following simplified component structure

Component Heirarchy

ChildC10 is basically a list with a bunch of check boxes for each item. The user can select one or many from this list.

ChildC1 contains a button when clicked should select the items checked in ChildC10. How do I do this using React, Redux.

Upvotes: 0

Views: 526

Answers (1)

Alexandre Rivest
Alexandre Rivest

Reputation: 694

Parent should have a local state containing selected element from the list. ChildC10 would have a props which is a function triggered on the onPress of an item of the list. This function would add/remove the item from the parent by using setState.

ChildC1 would have a props onPress which would do something with the state.

Parent would be something like this

export default class Parent extends Component {

  state = {
    selectedItems: [],
  }

  render() {
    return (
      <div>
        <ChildC10
            selectedItems={this.state.selectedItems}
            onItemPressed={(item) => {
              const currentList = this.state.selectedItems;
              //Find if item already in it
              //Modify (add or remove) the element from currentList
              this.setState({selectedItems: currentList})
          }}
        />
        <ChildC1 onButtonPress={() => /*do the thing you want to do with the selectedItems. You have access to it in the state*/}/>
      </div>
    );
  }
}

you can use the structure you want to store the selectedItems. If you want to call an action to make an API call, I would call the action in Parent. I wouldn't bind ChildC1 to Redux because it's a dumb component which should do only visual stuff. the container (Parent in your case) are the one who should have the logic.

If it wasn't the case, forget about the last paragraph and just check the code :P

Hope it helps!

Upvotes: 1

Related Questions