How to create optional parameter on path and activestyle in react router v4/react-router-dom?

时间:2017-06-09 12:49:21

标签: javascript reactjs react-router-v4 react-router-dom

I want to pass an optional parameter on my route, this is my code that does not work from the root component,, the filter is optional, i tried /(:filter) it doesnt work:

<BrowserRouter>
    <Route path="/:filter?" component={App}/>
</BrowserRouter>

This code is on my footer component that uses FilterLink which only uses NavLink:

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

It's working but the style only affects the root component or localhost:3000/ (the root)

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

2 个答案:

答案 0 :(得分:1)

只需将以下内容添加(精确)到NavLink中即可:

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

答案 1 :(得分:0)

您可以指定另一个没有过滤器参数的路线:

<BrowserRouter>
    <Route exact={true} path="/" component={App}/>
    <Route path="/:filter" component={App}/>
</BrowserRouter>