cross icon
WebHow to handle dynamic routing with params

How to handle dynamic routing with params

4 mins Read
mainImg

Build with Radial Code

Radial Code Enterprise gives you the power to create, deploy and manage sites collaboratively at scale while you focus on your business. See all services.

Introduction to Dynamic Routing in React

Dynamic routing allows you to create routes that are not statically defined but instead are created based on parameters in the URL. These parameters could represent anything from a user’s profile ID to a blog post’s unique identifier.

For example, in a blog app, you might have a URL like /posts/:id, where id is a dynamic parameter that represents a specific post.

React's useEffect and useState hooks , combined with the native browser’s window.location, provide all the tools necessary to handle dynamic routing and parameters without requiring an external router.

Setting Up the Basic Project

image-name

Before diving into dynamic routing, let's set up a simple React project. If you don’t already have a React project, you can quickly set one up using create-react-app.

npx create-react-app dynamic-routing
cd dynamic-routing
npm start;

This command will initialize a new React application and launch the development server, allowing you to start building and testing your application immediately." Now, we’re ready to add dynamic routes to our app.

Using for window.location Dynamic Routes

image-name

In a typical React app, you would use React Router for handling routes, but we can simulate this process manually by leveraging the window.location object.

Handling Parameters in the URL

We will create a dynamic route where the URL will contain a parameter. For example, /post/:id , where :id is the dynamic parameter.

To extract the parameter from the URL, we can use the browser's window.location API.

import React, { useEffect, useState } from 'react';

function App() {
  const [postId, setPostId] = useState(null);

  useEffect(() => {
    const path = window.location.pathname;
    const id = path.split('/')[2];
  }, []);

  return (
    <div><h1>Post {postId}</h1><p>This is the page for post {postId}.</p></div>
  );
}

export default App;

In this example:

  • We use window.location.pathname to access the current URL’s path.
  • split('/')[2] extracts the dynamic part (the id parameter) from the URL.

Handling Dynamic Routes

image-name

Let’s create a more complex example. Imagine we are building a blog, and we want to display a different post based on the URL. Each post has a unique identifier, such as /posts/:id.

import React, { useEffect, useState } from 'react';

const posts = [
  { id: 1, title: 'React Basics', content: 'Learn the basics of React' },
  { id: 2, title: 'Advanced React', content: 'Master advanced React concepts' },
  { id: 3, title: 'State Management', content: 'Explore state management in React' },
];

function Post() {
  const [post, setPost] = useState(null);

  useEffect(() => {
    const path = window.location.pathname;
    const postId = path.split('/')[2]; 
   // Simulating fetching the post based on the ID
    const selectedPost = posts.find((post) => post.id === parseInt(postId));
    setPost(selectedPost);
  }, []);

  return (
    <div>
      {post ? (
        <><h1>{post.title}</h1><p>{post.content}</p></>
      ) : (
        <p>Post not found</p>
      )}
    </div>
  );
}

export default Post;

In this case:

  • We define an array posts to simulate fetching data.
  • We extract the post ID from the URL, then use the find() method to match it with the correct post.

Navigation Without React Router

image-name

Now that we have our dynamic routes working, let’s implement a way to navigate between posts. We can use window.location.href to change the URL and simulate navigation between pages.

import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to the Blog</h1>
      <button onClick={() => (window.location.href = '/posts/1')}>Post 1</button>
      <button onClick={() => (window.location.href = '/posts/2')}>Post 2</button>
      <button onClick={() => (window.location.href = '/posts/3')}>Post 3</button>
    </div>
  );
}

export default App;

Improving the User Experience

image-name

Using window.location.href causes a full page reload, which is not ideal for a smooth user experience. To avoid reloading the entire page, you can use the window.history.pushState() method.

This method allows you to modify the URL without causing a page reload.

import React from 'react';

function App() {
  const navigateToPost = (id) => {
    window.history.pushState(null, '', `/posts/${id}`);
    window.dispatchEvent(new Event('popstate'));
  };

  return (
    <div>
    <h1>Welcome to the Blog</h1>
   <button onClick={() => navigateToPost(1)}>Post 1</button>
   <button onClick={() => navigateToPost(2)}>Post 2</button>
   <button onClick={() => navigateToPost(3)}>Post 3</button> 
    </div>
  );
}

export default App;

Conclusion

In this tutorial, we’ve seen how to handle dynamic routing with parameters in React without relying on a third-party routing library like React Router. By using window.location.pathname and window.history.pushState(), we can manage URL parameters and simulate navigation between different routes. While using React Router would make these tasks much simpler and more maintainable, understanding these native browser APIs can help you create custom solutions when needed.

cta

Share this

whatsapp
whatsapp
whatsapp
whatsapp
whatsapp

Keep Reading

Stay up to date with all news & articles.

Email address

Copyright @2025. All rights reserved | Radial Code