0

Hello I'm new with react and I'm trying to load content in <API-Result/> depending on what is clicked in the <Navigation>. I'm not sure how I can fire an Event in <Navigation> that communicates with <Api-Result/> and display the right content. How can I inform <Api-Result/> what in was clicked ?

There is no relation between:

  • parent to child
  • child to parent

My structure in my <App> is

<Header>
 <Navigation />  //<----- here is menu
     ...
</Header>

<Content Grid>
    <Api-Result /> //<----- here is the content
</Content Grid>
Samy
  • 1,013
  • 3
  • 15
  • 25
  • Possible duplicate of [Detect click outside React component](https://stackoverflow.com/questions/32553158/detect-click-outside-react-component) – lux Jun 19 '17 at 19:34

1 Answers1

1

The general solution is to make a parent somewhere up the tree that delegates the data and actions to its children. Since React models itself as a "tree", it means that at some point these components will share a parent. Let's just say it's called <AppContainer>.

<AppContainer>   <-- this will delegate the data to the components below it
  <Header>
    <Navigation />
  </Header>
  <Content Grid>
    <ApiResult />
  </Content Grid>
</AppContainer>

You then hoist the functions up to the <AppContainer>, which delegates the data to the components below it. Suppose clicking the menu shows "saved" items. You might model behavior like this:

class AppContainer extends Component {
  state = { showSaved: true };

  onMenuClick = () => {
    this.setState({ showSaved: true });  // example
  };

  render() {
    return (
      <div>
      <Header>
        <Navigation
          showSaved={this.state.showSaved}
          onMenuClick={this.onMenuClick}
        />
      </Header>
      <ContentGrid>
        <ApiResult menuClicked={this.state.showSaved} />
      </ContentGrid>
      </div>
    );
  }
}

This will allow you to access that variable in both <ApiResult> and <Navigation>. When that variable is changed in the state, it will trigger re-renders to both, ensuring they are up to date.

corvid
  • 10,733
  • 11
  • 61
  • 130