Setting up dynamic routes in your React JS project.
Are you trying to set some dynamic routes in your application? Have you been thinking if it is possible to derive some routes based on variables in react application? Well, the answer is yes and we just need to know how to make the most of react-router-dom. Let me share the step-by-step process of setting up some dynamic routes. Follow the below steps without any delay.
Create a react application using the following command:
npx create-react-app portfolio
To check if the app is successfully running, open a terminal and run the below command.
npm run start
This will open your application in port 3000. Opens a default browser window to url - localhost:3000
You can see the react logo animated to spin and some links to learn the react js from its official docs.
Get back to the code and add some folders to form some structure for coding further, in the source 'src' folder of the project. Firstly, let us put in some pages to configure routes.
Create some components and render some basic tags. I have created two components, one being the about page. We might not need this page for our project. However, this is to configure the routes in the application. I later renamed this component to Admin.
Let us configure the routes on the app.js. We shall import BrowserRouter from react-router-dom to configure routes. Wrap the component in BrowserRouter and use the routes inside this. So, the App.js would look like the below code snippet.
The idea of my project is to render the list of pages on the home page as links to the respective details page. And we have the admin page to be able to add blog posts from a custom rich text editor. In order to do that, I have created a JSON file for soem mock data. This is to serve some data from local env and check the feasibility of how we can use the html-react-parser to render the html strings into react components in our project.
The current posts.json looks like this:
Now that we have some dummy data to render, let us render the titles on the home page using "Link" from react-router-dom as shown below.
In order to have this Link work for us, we have to add another dynamic route in App.js.
<Route path="post/:id" element={ <Post />} />
Let me show how the application turns after adding this route and links to titles.
From the above image, you can see that the route is derived from the title of the post. Finally, we have achieved the dynamic routes for the project. That's all in this post. Thanks for reading.
I hope this was helpful. Thank you. Happy Learning!