Active link with React-Router?

I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

Answers:

Answer

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

Answer

I know I'm kind of late to the party, but I handle this by setting an inline style :focus {whatever your styles are} I handle most styling inline, but I'm pretty sure this will work in a regular stylesheet too. just use

:focus

instead of

:active

EDIT

I, for a few reasons (mostly embedded software), can't use css style sheets. So I've grown to love inline styling (contrary to opinion, inline styles have worked well for a project with about 8000 lines of code spanning 37 files, with no performance impact). But unfortunately, the :active selector is bugged when using it inline like this, so I use the above method.

Another way to do this, because I know inline styles are kind of frowned upon, is to make a css active class with the styles you'd like for the nav-element, and keep a state variable to track your current page as high up in scope as your comfortable with (preferably root component), and update it when user navigates to another page. This can be done by wrapping <Redirect/> or <Link to={}/> with a functional component that handles updating state and navigation, and in your navigation component, check if the nav-element your rendering matches the current page, and if so, append your active css class to it.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.