In this article we are creating dynamic routes and components using ReactJS based on JSON data.
You can refer the example here:
https://github.com/KtreeOpenSource/ReactExamples/tree/master/dynamicroutesandcomponentsdemo
Step:1
Create react application by running the command.
1npx create-react-app dynamicroutesandcomponentsdemo
This will create dynamicroutes and componentsdemo react repository
Step:2
Install react-router-dom by running the command.
1npm install --save react-router-dom
This will create dynamicroutes and componentsdemo react repository
Step:3
Import router in App.js.
1.src/App.js
1import { BrowserRouter as Router, Route, Link } from "react-router-dom";2class App extends Component {3 render() {4 return (5 <div className="App">6 <h1>Create Dynamic Routes And Components Demo</h1>7 <Router></Router>8 </div>9 );10 }11}12export default App;
Step:4
Create dynamic routes and components data in the form of json array.
1.src/DynamicComponentsData.js
1let components = [{2 "title": "Home",3 "content": "Rendered Home Component",4 "route": "/"5}, {6 "title": "Test1",7 "content": "Rendered Test1 Component",8 "route": "/test1"9}, {10 "title": "Test2",11 "content": "Rendered Test2 Component",12 "route": "/test2"13}, {14 "title": "Test3",15 "content": "Rendered Test3 Component",16 "route": "/test3"17}]18export default components
Step:5
Create Dynamic component to print the data from json.
1.src/DynamicComponent.js
1import React, { Component } from 'react';2class DynamicComponent extends Component {3 render() {4 const { title, content } = this.props5 return (6 <div>7 <h1>{title}</h1>8 <p>{content}</p>9 </div>10 )11 }12}13export default DynamicComponent
Step:6
Creating dynamic routes and rendering the component by loop the DynamicComponentsData.js data.
1.src/App.js
1import React, { Component } from 'react';2import './App.css';3import { BrowserRouter as Router, Route, NavLink } from "react-router-dom";4import DynamicComponentsData from './DynamicComponentsData';5import DynamicComponent from './DynamicComponent';6class App extends Component {7 render() {8 let dynamicComponents = DynamicComponentsData;9 return (10 <div className="App">11 <h1>Create Dynamic Routes And Components Demo</h1>12 <Router>13 <div>14 <div>15 {16 dynamicComponents.map((item, index) => {17 return <div key={index}><NavLink exact activeClassName="selected" to={item.route}>{item.title}</NavLink></div>18 })19 }20 </div>21 <div>22 {23 dynamicComponents.map((item, index) => {24 return <Route exact key={index} path={item.route} component={() => <DynamicComponent title={item.title} content={item.content} />} />25 })26 }27 </div>28 </div>29 </Router>30 </div>31 );32 }33}34export default App;



