What is the good way to communicate between different components in React which are not children of one of them.
For example, this is my structure :
class App extends React.Component {
render() {
return (
<div className="App">
<SideBar title="My Sidebar"/>
<SearchBox/>
</div>
);
}
};
class SideBar extends React.Component {
constructor(props) {
super(props);
}
Toggle = () => {
this.refs.leftNav.toggle();
}
render() {
return (
<LeftNav ref="leftNav" className="sidebar">
<MenuItem index={0}>A</MenuItem>
<MenuItem index={1}>B</MenuItem>
</LeftNav>
);
}
}
class SearchBox extends React.Component {
constructor(props) {
super(props);
}
handleClick = (event) => {
this.refs.leftNav.Toggle(); // Doesn't work obsviously...
}
render() {
return (
<div onClick={this.handleClick}>
Hello
</div>
);
}
I try to make Searchbox communicate with Sidebar because an element of SearchBox (in this case, the main <div>
) has to toggle the <SideNav>
when it gets clicked. However I don't see an easy way to do that and what is the right and recommended approach to do this kind of things ?