Sayeed Afridi
Sayeed Afridi

Reputation: 376

Nested Routing with url param is not working in react-router-dom

I'm setting up nested routes within React-router-dom (v5.0.1), but it (route /primary/:id) is not working whenever I try and access one of the nested routes.

Nested route looks like..

const id = ({match}) =>  (
    <div>
        with id {match.params.id}
    </div>
)

const primary = ({match}) => (
    <div>
        This is the Primary route
        <br/>
        <Link to='/primary/one'>Primary with id</Link>
        <Route path='/primary/:id' component={id} />
    </div>
)

I cannot access the id component. I call the primary component in Routes component.

const Routes = () => {
    return(
        <Router>
            <Route exact path='/' component={main} />
            <Route exact path='/primary' component={primary} />    
        </Router>
    )
}

And Routes are called in App component as follows.

function App() {
  return (
    <div className="App">
      <Routes />
    </div>
  );
}

Upvotes: 2

Views: 2094

Answers (2)

Dixit Savaliya
Dixit Savaliya

Reputation: 413

You just put this code in your routes:

const Routes = () => {
    return(
        <Router>
            <Route exact path='/' component={main} />
            <Route exact path='/primary/:id' component={primary} />    
        </Router>
    )
}

Upvotes: 0

Pavindu
Pavindu

Reputation: 3112

Define two Routes for primary and id components as follows.


const id = () =>  (
    <div>
        with id {props.id}
    </div>
)

const primary = () => (
    <div>
        This is the Primary route
        <br/>
        {
          props.match.params.id ? 
            <id id={props.match.params.id}/>
         : ""
        }

        <Link to='/primary/one'>Primary with id</Link>
    </div>
)
const Routes = () => {
    return(
        <Router>
            <Route exact path='/' component={main} /> 
            <Route exact path='/primary' component={primary} />
            <Route exact path='/primary/:id' component={id} />
        </Router>
    )
}

EDIT The below is not tested. Try if this works.

const primary = ({match}) => (
    <div>
        This is the Primary route
        <br/>
        <Link to='/primary/one'>Primary with id</Link>
        {<Route path='/primary/:id' component={id} />}
    </div>
)

Upvotes: 2

Related Questions