Example of react router DOM (8) sidebar

In the official example of react router DOM, sidebar is a very easy example to implement. The core of odd implementation is to show two groups of Routes.

The rendering of this example is as follows:

Related core code:

import React, {Component} from 'react';
import {
    BrowserRouter as Router,
    Route,
    Link,
    Switch,
    Redirect
} from 'react-router-dom';

const routes = [
    { path: '/',
        exact: true,
        sidebar: () => <div>home!</div>,
        main: () => <h2>Home</h2>
    },
    { path: '/bubblegum',
        sidebar: () => <div>bubblegum!</div>,
        main: () => <h2>Bubblegum</h2>
    },
    { path: '/shoelaces',
        sidebar: () => <div>shoelaces!</div>,
        main: () => <h2>Shoelaces</h2>
    }
]


class App extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <Router>
                <div style={{display:'flex'}}>
                    <div style={{width: '200px',backgroundColor: '#cccccc'}}>
                        <ul>
                            <li><Link to='/'>Home</Link></li>
                            <li><Link to='/bubblegum'>Bubblegum</Link></li>
                            <li><Link to='/shoelaces'>Shoelaces</Link></li>
                        </ul>
                        {
                            routes.map((item,index)=>{
                                return (
                                    <Route exact={item.exact} key={index} path={item.path} component={item.sidebar}/>
                                )
                            })
                        }
                    </div>
                    <div style={{flex: 1}}>
                        {
                            routes.map((item,index)=>{
                                return (
                                    <Route exact={item.exact} key={index} path={item.path} component={item.main}/>
                                )
                            })
                        }
                    </div>
                </div>
            </Router>
        );
    }
}


export default App;

Overall realization idea:
It is a relatively simple routing method. A Link component corresponds to two Route components, one in the side bar area and one in the main view area on the right.

Route is displayed through two map traversals of routes array!

The github address for this example: https://github.com/liwudi/react-router-dom8.git

Tags: React github git

Posted on Tue, 31 Mar 2020 16:00:08 -0700 by thepip3r