简体   繁体   中英

How to create optional parameter on path and activestyle in 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>

Simply, you could add ( exact ) to the NavLink as the following :

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

You could just specify another route with no filter param:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM