ashish Kumar
ashish Kumar

Reputation: 33

How to pass props from unrelated component

I need to plot a table using data from header component ( 2 drop-downs & one Apply button), while header, table section & footer are unrelated to each other I have tried to create an array in separate Utils file, which is populated when Apply button is hit, it is passed as

<Table data={utils.sortArray}/>

While data is populating sortArray when Apply button is hit in header component, it is showing length 0 Still When Apply button is hit, new array data should get passed to table component

Upvotes: 2

Views: 849

Answers (1)

smashed-potatoes
smashed-potatoes

Reputation: 2222

If you need the table to update based on input in the header the components aren't really unrelated (they are related through the data they have in common / are sharing).

To communicate between the two you will need a way to pass the data - the logical approach is to have the parent component coordinate between the two as it is contextually aware of both. In this case, you can:

  1. Pass callback a prop to your header component that you call with the required data
  2. Store the data sent in the callback in the parent's state
  3. Pass the state data to your Table.

E.g., in your parent component:

state = {
  sortArray: '', // What ever your default value is
}

onSort = (sortArray) => {
  this.setState({
    sortArray,
  });
}

render() {
  ...
  <Header onSort={this.onSort} />
  ...
  <Table sortArray={this.state.sortArray} />
  ...
}

And then call onSort in your header with the required value as needed.

Upvotes: 3

Related Questions