Search code examples
reactjsreduxreact-routerreact-reduxchildren

Redux + React : react router only rendering index route


I have tried following the answer on this question but to no avail. I am trying to use react router and nested routes to render different layouts depending on the configuration of the router. But the route with path="/" always shows regardless of the URL that is present. Here is the router that I am using.

        <Route component={App}>
            <Route component={LayoutOne}>
                <Route path="/" component={ComponentOne}/>
            </Route>
            <Route component={LayoutTwo}>
                <Route path="category" component={ComponentTwo}/>
            </Route>
        </Route>

And here is the App file that I use to map the dispatch to the props, and connect.

function mapStateToProps(state, ownProps){
    return{
        exampleProp: state.exampleProp,
    };
}

function mapDispatchToProps(dispatch){
    return bindActionCreators(actionCreators, dispatch);
}


const App = connect(mapStateToProps, mapDispatchToProps)(MainLayout);

export default App;

Here is the main layout MainLayout as seen above.

export default class MainLayout extends Component {
    render(){
       <div className="main-layout">
            {this.props.children}
       </div>
    }
}

LayoutOne and LayoutTwo(has been omitted for brevity) are simple class rappers as follows.

export default class LayoutOne extends Component{ render(){ return( {this.props.children} ) } }

And here the ComponentOne and ComponentTwo respectively are just simple components.

My problem is that only ComponentOne renders regardless of what URL is present. How do I fix this issue so that I could use nested routes as shown above? Your help would be much appreciated. If you need any additional information, please ask and I will do my best to update the question with the required information. Thanks.


Solution

  • The problem you're having is that the index route, i.e. '/', is being matched first in your route tree, and because it matches any route, it is the route that gets rendered every time.

    You can fix this by moving the Route with path="category" above the one with path="/". This way the more detailed route option gets checked first. I would also recommend changing path="category" to path="/category" just for clarity's sake as both are root level routes.