skip to Main Content

I’m facing an issue with React-Router where navigating to a specific URL with a dynamic parameter is rendering the wrong component. Specifically, when navigating to "http://localhost:3001/Create/4", the Create component is being rendered instead of the expected Blogdetails component associated with the ID 4.

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Components/Home';
import Blogdetails from './Components/Blogdetails';
import Create from './Components/Create';

function App() {
  return (
    <Router>
      <div className="App">
        {/* Other components or content */}
        <Switch>
          <Route exact path='/' component={Home} />
          <Route path='/blogs/:id' component={Blogdetails} />
          <Route path='/Create' component={Create} />
        </Switch>
        {/* Other components or content */}
      </div>
    </Router>
  );
}

export default App;
import React from "react";
import { useParams } from "react-router-dom";

const Blogdetails = () => {
    const { id } = useParams();
    return (
        <div className="blog-details">
            <h2>Blog Details - {id}</h2>
        </div>
    );
}

export default Blogdetails;

Despite rearranging the route order and verifying the useParams hook, the issue persists. Can someone help me identify what might be causing this unexpected behavior with React-Router?

Rearranging the route order in the <Switch> component to ensure the dynamic route ("/blogs/:id") is before the static route ("/Create"). Verified the implementation of the useParams hook in the Blogdetails component to correctly extract the id parameter from the URL. Checked for any conflicting routes or conflicting paths defined in other parts of the application.

Expected Outcome:

Upon navigating to "http://localhost:3001/Create/4", I expected the Blogdetails component to be rendered, displaying the details for the blog with ID 4. I anticipated that the route pattern "/blogs/:id" would match the URL and correctly render the Blogdetails component while extracting the id parameter.

Actual Result:

Instead of rendering the Blogdetails component, the application renders the Create component when navigating to "http://localhost:3001/Create/4". Despite reordering the routes and ensuring correct implementation of the useParams hook, the issue persists.

import React from "react";
import { Link } from "react-router-dom";





const Navbar = () =>{

    const handleClick = (e) => {
        console.log("Hello, World", e);
    }

    const handleClickAgain = (name, e) => {
        console.log("Hello " + name, e.target);
    }

    return(
         <nav className="navbar">
            <h1>The Magnum blog</h1>
            <div className="links">
                <Link to="/">Home</Link>
                <Link to="/Create" style={{
                    color: "white",
                    backgroundColor: "#f1356d",
                    borderRadius: "8px "
                }} onClick={handleClick}>New Blog</Link>
                <button onClick={(e) => {handleClickAgain("Mario",e)}}>Another Blog</button>
            </div>
         </nav>
         
    )
}


export default Navbar;
import { Link } from "react-router-dom";




const BlogList = ({ blogs, title}) => {
    
    
    return(
       <div className="blog-list">
        <h2>{ title }</h2>
        {blogs.map((blog) => (
                <div className="blog-preview" key={blog.id}>
                    <Link to = {`/blogs/${blog.id}`}>
                    <h2>{blog.title}</h2>
                    <p>Writtern By {blog.author}</p>
                    </Link>
                </div>
            ))}
       </div>
    )
} 

export default BlogList;

2

Answers


  1. If you would like for the path "/create/4" to be matched and render the BlogDetails then you need to render a route that can match it. Currently the BlogDetails component is rendered only on a "/blogs/:id" route, so the route "/create" is the next best match and the Create component is rendered.

    Add a "/create/:id" route path.

    function App() {
      return (
        <Router>
          <div className="App">
            {/* Other components or content */}
            <Switch>
              <Route
                path={['/blogs/:id', '/create/:id']} // <-- specify path array
                component={BlogDetails}
              />
              <Route path='/create' component={Create} />
              <Route path='/' component={Home} />
            </Switch>
            {/* Other components or content */}
          </div>
        </Router>
      );
    }
    
    Login or Signup to reply.
  2. Try going to the url /blogs/4 directly and if there is a blog with id 4, then it should render correctly.

    If you want the same effect with Create/4, then you would need to change your second route to Create/:id and corresponding links and onClick handlers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search