Jonathan Kumar
Jonathan Kumar

Reputation: 563

React Router v4 Nested Routing not working when in sub level

I'm trying to build a React App, this is the first time i'm working with react and so i don't know how to troubleshoot this. Basically what i need is to create routes for a link, let's say these are the following links.

/car
/car/sedan
/car/coupe

i have setup routing as so.

car.js

import React from 'react'
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'
import CoupeCar from './coupecar'
import SedanCar from './sedancar'

class Car extends React.Component {
    constructor(props){
        super(props);
    }

    render () {
        return (
            <div className="main_elem_container">
                <Router>
                    <Switch>
                        <Route path="/car" component={Car} />
                        <Route exact path="/car/sedan" component={SedanCar} />
                        <Route exact path="/car/coupe" component={CoupeCar} />
                    </Switch>
                </Router>
            </div>
        );  
    }
}

const Car = () => (
    <p>I'm a Car</p>
)

export default Car;

And the routing works i can visit /car/sedan and /car/coupe when i'm browsing through the navigation from /car but i cannot visit /car/sedan when im at the /car/coupe page and vice-versa.

The navigation just gets stuck and doesn't load, please let me know on how i can fix this i've even tried many options but all of them give me this result, at least if i knew how to debug this it'll be better, thanks.

Upvotes: 0

Views: 2168

Answers (2)

Prasanna D
Prasanna D

Reputation: 1

try this, the exact path should be placed as last option

<Router>
    <Switch>
        <Route path="/car/sedan" component={SedanCar} />
        <Route path="/car/coupe" component={CoupeCar} />
        <Route exact path="/car" component={Car} />
    </Switch>
</Router>

Upvotes: 0

devserkan
devserkan

Reputation: 17608

I don't know how your setup works partially, it should not with this config. What you need is:

<Router>
    <Switch>
        <Route exact path="/car" component={Car} />
        <Route path="/car/sedan" component={SedanCar} />
        <Route path="/car/coupe" component={CoupeCar} />
    </Switch>
</Router>

So, if only when you hit /car your Car component renders. For /car/sedan and /car/coupe you will see the related components. If you don't use exact for /car, /car/sedan and /car/coupe will render Car component no matter what.

Also, do not use same component names. You have two Car components. Rename the container something else, App maybe?

Upvotes: 1

Related Questions