0

First, I've tried fixing this issue using this: Multiple params with React Router. But there's def. things I do not get in this context. I'm fairly new to react-router-dom and I'm trying to have two params in the URL, like this: /:type/:projectid.

I have instantiated my <Link> like this, coming from an array of data:

let projectRoutePlaceholder = `${ele.type}/project${this.props.index}`

  return(
        <Router>
          <Link to={projectRoutePlaceholder}>
            ....
          </Link>
        </Router>
      );

When I hover on my content, I therefore have the route URL displaying on the bottom left of the browser. On my index.js file, I've set up my routes like this:

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <Route exact path='/' component={App} />
      <Route exact path='/index' component={ProjectIndex} />
      <Route exact path='/info' component={Info} />
      <Route exact path='/:type/:id' component={ProjectTemplate} />
    </Router>
  </React.StrictMode>,
  document.getElementById('root')

Now, two issues I'm not able to fix.

  1. When I click on a <Link> element, it does not send me to the ProjectTemplate component and it stays on the <Link> element. When I force (refresh the page with the exact route, e.g: commercial/project0), it works.
  2. When I click once again on the <Link> element, params gets concatenated (e.g: commercial/commercial/project0)

How can I fix these two issues?

cyruslk
  • 839
  • 3
  • 13
  • 25

1 Answers1

0
  1. With react-router-dom you only want to have 1 top level Router that wraps around your routes. Your Links would also have to come at some point in the child tree of that 1 router. The outer Router holds the context of your current route and causes state updates which is how your different routes come in to effect. Because you are wrapping every single Link with it's own Router, when you click on one of those Links, the Router wrapping them is the only one getting updated which doesn't have any child routes to update/show. If you get rid of these wrapping Routers from your Links and just keep the top level one around your Routes, this should fix the issues you are running in to.

  2. Change let projectRoutePlaceholder = `${ele.type}/project${this.props.index} to let projectRoutePlaceholder = `/${ele.type}/project${this.props.index} so that it has a leading slash at the beginning. If you don't put a leading slash, then react-router-dom will assume you want to append the url to the end of your current route which will cause the concatenation issue you're running in to. By adding a leading slash, you are telling react-router-dom to go directly to the route rather than append it.

Chris
  • 1,484
  • 1
  • 12
  • 19