I have a large website which has many sub websites under the main one. I have a SubNav that shows the name of the company's page we are currently visiting. As the user navigates between pages it should update the SubNav with the name.
This is what I have tried but to no avail.
Main Parent Root Component.
class AppRouter extends React.Component {
state = { companySelected: "Main Company" };
// this should update the company and name the SubNav bar
updateSelectedCompany = companySelected => {
console.log("updated selected", companySelected);
this.setState({ companySelected: companySelected });
};
render() {
return (
<Router history={history}>
<div>
<NavBar />
<SubNav companySelected={this.state.companySelected} />
<Switch>
<Route path="/" component={LandingPage} exact={true} />
<Route
path="/company/1"
component={SubCompany1}
exact={true}
updateSelectedCompny={this.companySelected}
/>
<Route
path="/company/2"
component={SubCompany2}
exact={true}
/>
</Switch>
<Footer />
</div>
</Router>
);
}
}
The SubCompany1 Page looks like this:
class SubCompany1 extends React.Component {
componentDidMount() {
this.setState({ companySelected: "Sub Company 1" });
console.log("Did Mount Sub Company1");
}
render() {
return (
<div>
<h1>Sub Company 1</h1>
</div>
);
}
}
Is this possible to pass each time a page is visited? I'm quite new to react and not entirely sure the best way to pass state between components.