Thursday, December 19, 2019

ReactJS - Multiple Layout In React Using React Router | Using multiple layouts for react-router components

React Router is a standard routing library for React.
In the first step, we will create two different layout files (named CommonLayout and DashboardLayout) and their respective routes to implement multiple layouts in React.

CommonLayout


import React, { Component } from 'react';
import {Route} from 'react-router-dom';

class CommonLayoutComponent extends React.Component{
    constructor(props){
        super(props);
        this.createRef = this.createRef.bind(this);
    }

    createRef(element) {
        console.log(element);
    }

    render() {
        return (
            <div key="dashboard">
                <div className="Content" ref={this.createRef}>
                    {this.props.children}
                </div>
            </div>
        );
    }
}

const CommonLayoutRoute = ({component: Component, ...rest}) => {
    return (
        <Route {...rest} render={matchProps => (
            <CommonLayoutComponent {...matchProps}>
                <Component {...matchProps} />
            </CommonLayoutComponent>
        )} />
    )
};

export default CommonLayoutRoute;

DashboardLayout


import React, { Component } from 'react';
import { Route } from 'react-router-dom';

const DashboardLayoutRoute = ({component: Component, ...rest}) => {
    return (
        <Route {...rest} render={matchProps => (
            <div>
                <h3>Dashboard Layout</h3>
                <Component {...matchProps} />
            </div>
        )} />
    )
};

export default DashboardLayoutRoute;
Now, update your App.js file to use both - the layout and the component - as below.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';

/** Layouts **/
import CommonLayoutRoute from "./CommonLayoutRoute";
import DashboardLayoutRoute from "./DashboardLayout";

/** Components **/
import LayoutPage1 from './LayoutPage1';
import LayoutPage2 from './LayoutPage2'

/*
   App
 */
class App extends Component {
    render() {
        return (
            <Router>
                <Switch>
                    <Route exact path="/">
                        <Redirect to="/layout1" />
                    </Route>
                    <CommonLayoutRoute path="/layout1" component={LayoutPage1} />
                    <DashboardRoute path="/layout2" component={LayoutPage2} />
                </Switch>
            </Router>
        );
    }
}

export default App;
Here, we have updated the App.js file as defined in the route. When we route to /layout1, then CommonLayoutRoute (our first layout) will be used as the master page for the component LayoutPage1. On the other hand, when we route to /layout2, then our second layout, i.e., DashbaordLayoutRoute will be used as the master page for the component LayoutPage2.

No comments:

Post a Comment