I am new to react. I am using react-route-dom and . I would like to change the colour of my NavBar functional component when the route changes.
In my NavBar component I am using the HOC (connect) from react-redux and withRouter from react-router to get route props and information from my redux store.
const mapStateToProps = (state) => {
return {
moduleCards: state.moduleCards
}
}
export default connect(mapStateToProps)(withRouter(NavBar));
Here is a snippet of how I am getting route information to then find the moduleCard entry and get it's colour.
const NavBar = (props) => {
console.log("Hello world?");
const modules = props.moduleCards.find(c => `/${c.name.replace(/ /g,'')}` === props.location.pathname);
const color = typeof modules !== 'undefined' ? modules.color : 'blue';
return (
<nav>
<div className={`nav-wrapper ${color} darken-2`}>
The problem is that the colour does not change when I change route. Can you please help with how to trigger a render on my NavBar component? Or if there is a better way to handle this?
Here is my root App component.
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<NavBar/>
<Switch>
<Route exact path='/' component={Home}/>
<ModuleRoutes/>
</Switch>
</div>
</BrowserRouter>
);
}
}
Here is a snap shot of my store, this is where I am grabbing the colour from.
const initialState = {
moduleCards: [
{ id: 0, name: 'Client Register', icon: 'person', color: 'red' },
{ id: 1, name: 'Property Register', icon: 'domain', color: 'blue' },
The colour is blue on the home page and unless I refresh it remains blue. When I refresh it rerenders and the navbar gets its correct colour.