I have two components in my index.js file (Header and Sidebar) like below
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import {
BrowserRouter as Router,
Route
} from "react-router-dom";
import './index.scss';
import './responsive.scss';
import Sidebar from './sidebar';
import Header from './header';
import Home from './home';
import Products from './products';
import Variant from './variant';
import Variety from './variety';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Router>
<div className="wrapper">
<Header />
<Sidebar />
<div id="content">
<Route exact path="/" component={Home} />
<Route path="/products" component={Products} />
<Route path="/variant" component={Variant} />
<Route path="/variety" component={Variety} />
</div>
</div>
</Router>
, document.getElementById('root'));
serviceWorker.unregister();
I have a button in my Header component and I want to add an onClick event handler to it, so when clicked the sidebar in Sidebar component would be toggled. Now my problem is that I can not connect these two components. I have even tried to use what is suggested in this link How To Pass Events Between Components, but the problem is that the event targets the change of all the elements defined in the children's components. I have read something about the createPortal() but it was suggested to access the DOM outside the component and since I am trying to access a component from another one I'm not sure if I should be doing that. Your help is appreciated in advance.
There are few ways.
You can do something like following
// IN MAIN FILE
state ={
sidebarOpen : false
}
<header toggleSidebar = { this.toggleSidebar} />
<sidebar sidebarOpen = { this.state.sidebarOpen} />
toggleSidebar(){
//UPDATE STATE
this.setState({
sidebarOpen : !(this.state.sidebarOpen)
})
}
// IN HEADER
onButtonClick(){
this.props.toggleSidebar()
}
IN SIDEBAR
componentWillReceiveProps(props){
//LOGIC FOR UPDATING SIDEBAR YOU WILL RECIEVE UPDATED STATE HERE
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With