javascript – React Router with – Ant Design Sider: how to populate content section with components for relevant menu item

I’m trying to use AntD menu sider like a tab panel.

I want to put components inside the content so that the content panel renders the related component when a menu item is clicked.

How do I get this structure to take components as the content for each menu item?

import React from 'react';
import { compose } from 'recompose';
import { Divider, Layout, Card, Tabs, Typography, Menu, Breadcrumb, Icon } from 'antd';
import { PasswordForgetForm } from '../Auth/Password/Forgot';


const { Title } = Typography
const { TabPane } = Tabs;
const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;


class Dashboard extends React.Component {
  state = {
    collapsed: false,
  };

  onCollapse = collapsed => {
    console.log(collapsed);
    this.setState({ collapsed });
  };

  render() {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        <Sider collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}>
          <div  />
          <Menu theme="light" defaultSelectedKeys={['1']} mode="inline" >

            <Menu.Item key="1">
              <Icon type="fire" />
              <span>Next item</span>
              <PasswordForgetForm />
            </Menu.Item>  
            <Menu.Item key="2">
              <Icon type="fire" />
              <span>Next item</span>
              <Another component to render in the content div />
            </Menu.Item>

          </Menu>
        </Sider>
        <Layout>
          <Header style={{ background: '#fff', padding: 0 }} />
          <Content style={{ margin: '0 16px', background: '#fff' }}>

            <div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
            RENDER RELEVANT COMPONENT HERE BASED ON MENU ITEM SELECTED
            </div>
          </Content>
          </Layout>
      </Layout>
    );
  }
}

export default Dashboard;

When I try to render this, no errors are thrown, but the content div does not update with the PasswordForgetForm that I specified as the content for the menu item.

I tried Chris’ suggestion below – which works fine to render the component for each of the different menu item content divs in the layout segment, however – the downside of this approach is that with every page refresh, the path goes to the content component for that particular menu item, instead of the test page which has the menu on it — and the content component with that relevant content. If this approach is endorsed as sensible, is there a way to keep the page refresh on the original page, rather than trying to go to a subset menu item url?

Update

I found this literature. I think this might be what I need to know, but the language is too technical for me to understand. Can anyone help with a plain english version of this subject matter?

I also found this tutorial which uses Pose to help with rendering. While this structure is what I’m trying to achieve, it looks like Pose has been deprecated. Does anyone know if its necessary to go beyond react-router to get this outcome, or is there a solution within react that I can look to implement?

This example is similar to what I want, but I can’t find anything that defines a sidebar (which seems to be an argument that is necessary to make this work).

I have also seen this post. While some of the answers are a copy and paste of the docs, I wonder if the answer by Adam Gering is closer to what I need. I’m trying to keep the Sider menu on the /dash route at all times. That url should not change – regardless of which menu item in the sider the user clicks BUT the content div in the /dash component should be updated to render the component at the route path I’ve specified.

APPLYING CHRIS’ SUGGESTION

Chris has kindly offered a suggestion below. I tried it, but the circumstance in which it does not perform as desired is when the menu item is clicked (and the relevant component correctly loads in the content div, but if I refresh the page, the refresh tries to load a page with a url that is for the component that is supposed to be inside the content div on the dashboard page.

import React from 'react';
import {
    BrowserRouter as Router,
    Route,
    Link,
    Switch,

  } from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import { compose } from 'recompose';
import { Divider, Layout, Card, Tabs, Typography, Menu, Breadcrumb, Icon } from 'antd';
import { withFirebase } from '../Firebase/Index';
import { AuthUserContext, withAuthorization, withEmailVerification } from '../Session/Index';

// import UserName from '../Users/UserName';
import Account from '../Account/Index';
import Test from '../Test/Index';



const { Title } = Typography
const { TabPane } = Tabs;
const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;


class Dashboard extends React.Component {
  state = {
    collapsed: false,
  };

  onCollapse = collapsed => {
    console.log(collapsed);
    this.setState({ collapsed });
  };

  render() {
    const {  loading } = this.state;
    // const dbUser = this.props.firebase.app.snapshot.data();
    // const user = Firebase.auth().currentUser;
    return (
    <AuthUserContext.Consumer>
      {authUser => (  

        <div>    
         {authUser.email}
          <Router>  
            <Layout style={{ minHeight: '100vh' }}>
              <Sider collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}>
                <div  />
                <Menu theme="light" defaultSelectedKeys={['1']} mode="inline" >
                  <SubMenu
                    key="sub1"
                    title={
                      <span>
                      <Icon type="user" />
                      <span>Profile</span>
                      </span>
                    }
                  >

                      <Menu.Item key="2"><Link to={ROUTES.ACCOUNT}>Account Settings</Link></Menu.Item>


                      <Menu.Item key="3"><Link to={ROUTES.TEST}>2nd content component</Link></Menu.Item>
</SubMenu>

                </Menu>
              </Sider>
              <Layout>

                <Header>                </Header>      
                <Content style={{ margin: '0 16px', background: '#fff' }}>

                  <div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
                      <Switch>
                          <Route path={ROUTES.ACCOUNT}>
                          <Account />
                          </Route>
                          <Route path={ROUTES.TEST}>
                          < Test />
                          </Route>

                      </Switch>    
                  </div>
                </Content>
                <Footer style={{ textAlign: 'center' }}>


                 test footer
                </Footer>
              </Layout>
            </Layout>
          </Router>  
        </div>
      )}
    </AuthUserContext.Consumer>  
    );
  }
}

export default Dashboard;

In my routes file, I have:

export const ACCOUNT = '/account';

I’ve also found this tutorial – which uses the same approach outlined above – and doesn’t get redirected in the same way that my code does on page refresh. The tutorial uses Route instead of BrowserRouter – but otherwise I can’t see any differences.

NEXT ATTEMPT

I saw this post (thanks Matt). I have tried to follow the suggestions in that post.

I removed the outer Router wrapper from the Dashboard page (there is a Router around App.js, which is where the route to Dashboard is setup).

Then, in my Dashboard, I changed the Content div to:

I added:

let match = useRouteMatch();

to the render method inside my Dashboard component (as shown here).

I added useRouteMatch to my import statement from react-router-dom.

This produces an error that says:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks

There is more message in the error above but stack overflow won’t allow me to post it because it has a short link

I don’t know what I’ve done wrong in these steps, but if I comment out the let statement, the page loads.

When I go to /Dashboard and click “account”, Im expecting the account component to render inside the content div I have in the layout on the Dashboard page. Instead, it redirects directly to a page at localhost3000/account (for which there is not page reference – it’s just a component to render inside the Dashboard page).

So this is worse than the problem I started with – because at least at the start, the redirect only happened on page refresh. Now it happens immediately.

I found this repo that has examples of each kind of route. I can’t see what it is doing that I am not.

This post seems to have had the same problem as me, and resolved it using the same approach as I have tried. It’s a post from 2018 so may the passage of time makes the approach outdated – but I can’t see any difference between what that post solutions implements and my original attempt.

NEXT ATTEMPT

I had thought I had found an approach that works in Lyubomir’s answer on this post.

I have:

<Menu.Item key="2">
                      <Link to=

{${this.props.match.url}/account}> Account Settings

Then in the div on the dash component where I want to display this component I have:

<div>
                      <Switch>
                          <Route exact path={`${this.props.match.url}/:account`} component={Account} />

This works. On page refresh, I can keep things working as they should.

HOWEVER, when I add a second menu item with:

<Menu.Item key="16">
                    <Link to={`${this.props.match.url}/learn`}>
                      <Icon type="solution" />
                      <span>Lern</span>
                    </Link>  
                  </Menu.Item>

Instead of rendering the Learning component when menu item for /learn is clicked (and the url bar changes to learn), the Account component is rendered. If i delete the account display from the switch statement, then I can have the correct learning component displayed.

With this attempt, I have the menu items working to match a Dashboard url extension (ie localhost/dash/account or localhost/dash/learn) for ONE menu item only. If I add a second menu item, the only way I can correctly render the 2nd component, is by deleting the first menu item. I am using switch with exact paths.

I want this solution to work with multiple menu items.

I have tried alternating path for url (eg:

<Link to={`${this.props.match.url}/learn`}>

is the same as:

<Link to={`${this.props.match.path}/learn`}>

I have read the explanation in this blog and while I don’t entirely understand these options. I have read this. It suggests the match statement is now a legacy method for rendering components (now that hooks are available). I can’t find any training materials that show how to use hooks to achieve the expected outcome.

Leave a Comment