Hello Friends,

Welcome To Infinitbility!

This article will help you to create dynamic route in react like server rendering, here we are using react-router and react-router-dom to manage route in react.

In this article, I will share Routes component to manage routes with routes props, every time it will create routes when props change.

Let’s start today topic how to render dynamic route in React

Step 1: Import Component

First, we have to import all component in routes files and create object with their key, because we have to access component dynamically.

routes.jsx

import React, { useEffect, useState } from 'react';
import {Switch, Route } from 'react-router-dom';

import ForgotPassword from './common/forgotPaasword';
import Login from './common/login';
import CreateProfile from './clinician/createProfile';
import Dashboard from './clinician/dashboard';

const ComponentList = {
    'AdminCreateProfile'            :   AdminCreateProfile,
    'AdminManageProfile'            :   AdminManageProfile,
};

Step 2: Server rendering

Here we are assuming route file getting route array from props.


import React, { useEffect, useState } from 'react';
import {Switch, Route } from 'react-router-dom';

import ForgotPassword from './common/forgotPaasword';
import Login from './common/login';
import CreateProfile from './clinician/createProfile';
import Dashboard from './clinician/dashboard';

const ComponentList = {
    'AdminCreateProfile'            :   AdminCreateProfile,
    'AdminManageProfile'            :   AdminManageProfile,
};

const Router = (props) =>  {
    const [ routes, setRoutes ] = useState(props.routes);

    useEffect(() => {
        //console.log('routes changed', props.routes);
        setRoutes(props.routes);
    }, [props.routes])

    return (
        <Switch>
            
            <Route exact path={`/`} component={Login} />
            <Route path='/forgot-password' component={ForgotPassword}/>

            {
                routes != null && routes != '' && 
                routes.length > 0 && routes.map((route, index) => (
                
                    /* check if the component exists for each route */
                    typeof(ComponentList[route.component]) != 'undefined' ? 
                        <Route 
                            exact
                            key={index}  
                            path={route.route_name} 
                            component={ComponentList[route.component]} 
                        />
                    : null
                
                ))
            }

        </Switch>
    )
}

export default Router;

Thanks for reading…

May be you are looking for it

How to show bottom in react datepicker

How to generate dynamic route in React

Deploy React Application on Ubuntu Apache