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.
npx create-react-app dynamicroutesandcomponentsdemo
This will create dynamicroutes and componentsdemo react repository
Step:2
Install react-router-dom by running the command.
npm install –save react-router-dom
This will create dynamicroutes and componentsdemo react repository
Step:3
Import router in App.js.
.src/App.js
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
class App extends Component {
render() {
return (
<div className="App">
<h1>Create Dynamic Routes And Components Demo</h1>
<Router></Router>
</div>
);
}
}
export default App;
Step:4
Create dynamic routes and components data in the form of json array.
.src/DynamicComponentsData.js
let components = [{
"title": "Home",
"content": "Rendered Home Component",
"route": "/"
}, {
"title": "Test1",
"content": "Rendered Test1 Component",
"route": "/test1"
}, {
"title": "Test2",
"content": "Rendered Test2 Component",
"route": "/test2"
}, {
"title": "Test3",
"content": "Rendered Test3 Component",
"route": "/test3"
}]
export default components
Step:5
Create Dynamic component to print the data from json.
.src/DynamicComponent.js
import React, { Component } from ‘react’;
class DynamicComponent extends Component {
render() {
const { title, content } = this.props
return (
<div>
<h1>{title}</h1>
<p>{content}</p>
</div>
)
}
}
export default DynamicComponent
Step:6
Creating dynamic routes and rendering the component by loop the DynamicComponentsData.js data.
.src/App.js
import React, { Component } from ‘react’;
import ‘./App.css’;
import { BrowserRouter as Router, Route, NavLink } from "react-router-dom";
import DynamicComponentsData from ‘./DynamicComponentsData’;
import DynamicComponent from ‘./DynamicComponent’;
class App extends Component {
render() {
let dynamicComponents = DynamicComponentsData;
return (
<div className="App">
<h1>Create Dynamic Routes And Components Demo</h1>
<Router>
<div>
<div>
{
dynamicComponents.map((item, index) => {
return <div key={index}><NavLink exact activeClassName="selected" to={item.route}>{item.title}</NavLink></div>
})
}
</div>
<div>
{
dynamicComponents.map((item, index) => {
return <Route exact key={index} path={item.route} component={() => <DynamicComponent title={item.title} content={item.content} />} />
})
}
</div>
</div>
</Router>
</div>
);
}
}
export default App;