React Router: Active Link not matching the URL

Viewed 722

I am following the example of react-redux: Adding React Router to the Project

components/Root.js


import React from 'react';
import { Provider } from 'react-redux';
import App from './App'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Root = ({ store }) => (
    <Provider store={store}>
        <Router>
            <Switch>
                <Route exact path='/' component={ App }/>
                <Route path="/:filter" component={ App }/>
            </Switch>
        </Router>
    </Provider>
);

export default Root;

components/Footer.js

import React from 'react'
import FilterLink from '../containers/FilterLink'

const Footer = () => (
  <p>
    Show:
    {" "}
    <FilterLink filter="all">
      All
    </FilterLink>
    {", "}
    <FilterLink filter="active">
      Active
    </FilterLink>
    {", "}
    <FilterLink filter="completed">
      Completed
    </FilterLink>
  </p>
)

export default Footer

containers/FilterLink.js

import React from 'react';
import { NavLink } from 'react-router-dom'

const FilterLink = ({ filter, children }) => {

    console.log("filter: "+filter);
    console.log("children: "+children);

    return (
      <NavLink
        to={filter === 'all' ? '' : filter}
        activeStyle={{
          textDecoration: 'none',
          color: 'black',
        }}
      >
        {children}
      </NavLink>
    );

}

export default FilterLink;

The results i get are:

screenshot_20171109_195739

screenshot_20171109_195723

As per the code the active link should be same as the URL. Even the URL shows "localhost:3008/active" the active link shows as "all" and similar to completed.

Whats going wrong and why the corresponding link is not getting activated as per the URL.

1 Answers

Try adding a /

const FilterLink = ({ filter, children }) => {

  console.log("filter: "+filter);
  console.log("children: "+children);

  return (
    <NavLink
      // / is added via string interpolation
      to={filter === 'all' ? '' : `/${filter}`}
      activeStyle={{
        textDecoration: 'none',
        color: 'black',
      }}
    >
      {children}
    </NavLink>
  );

}

or

import React from 'react'
import FilterLink from '../containers/FilterLink'

const Footer = () => (
  <p>
    Show:
    {" "}
    <FilterLink filter="/all">
      All
    </FilterLink>
    {", "}
    <FilterLink filter="/active">
      Active
    </FilterLink>
    {", "}
    <FilterLink filter="/completed">
      Completed
    </FilterLink>
  </p>
)

export default Footer

and update the check in the FilterLink Component:

to={filter === '/all' ? '' : filter}
Related