I am trying to style a Navbar Link depending on the current path in my React App, if the path is /create or /add it should change it's styling. Here is what I have so far in my header component:
<div
id="createLink"
className={this.state.createClassName}
onClick={() => this.handleModalToggle()}
>
CREATE
</div>
handleActiveLink= () => {
let path = this.props.location.pathname
if (path === "/add" | path === "/create") {
this.setState({createClassName: "nav-link-active"})
} else {
this.setState({ createClassName: "nav-link" })
}
};
componentDidMount() {
this.handleActiveLink()
}
This works but only after I refresh the page which makes sense but it's not what I want. So I am looking for a way to change the className before even rendered and get the path first (I am using withRouter from react-router-dom)
NavLink
instead. github.com/ReactTraining/react-router/blob/master/packages/… – demkovychactiveClassName
. Don't reinvent the wheel and add more of them. – Drew Reese