jyotishman saikia
jyotishman saikia

Reputation: 2195

React router 4 nested routes not working

I am trying to create a nested route - When user logs in it opens dashboard and when dashboard open i want to create a nested route by making a side menu and change the content at the right but not able to do. When I am trying to access the post page in dashboard it is not opening.

import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../_actions';
import { PostPage } from './PostPage';
import { HomePage } from '../HomePage';

class DashboardPage extends React.Component {
  render() {
    const { url } = this.props;
    return (
      <div>
        <h1>BasicRouting</h1>
        <p>With the help of "Match" Component we can specify the Component we want to render for a particular pattern of the App location/window.pathname.</p>
        <p>Select a level from Left Navigation to view the content, also notice the change in URL.</p>
        <div className="rightContent">
          <p>Second Level Content will appear here:</p>
          <Route path={`${this.props.match.url}/post`} component={PostPage} />
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  console.log(state)
  return {
      isLoggedIn: state
  };
}

const connectedDashboardPage = connect(mapStateToProps)(DashboardPage);
export { connectedDashboardPage as DashboardPage };

Upvotes: 0

Views: 973

Answers (1)

Yuanpeng.Zheng
Yuanpeng.Zheng

Reputation: 117

There are several problems in your code.

  1. You import { Switch ... } from 'react-router-dom', but never used it afterward.
  2. If you want to call the route in upper/parent components, you need to import { withRouter } to wrap the redux connected class, something like,

    const connectedDashboardPage = connect(mapStateToProps)(DashboardPage);
    const withRouterConnectedDashboardPage = 
    withRouter(connectedDashboardPage);
    export default withRouterConnectedDashboardPage;
    

Final suggestion, read through the tutorial here: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf & always refer to: https://reacttraining.com/react-router/

Upvotes: 1

Related Questions