0

I am building a Blog app and I am trying to pass id with url for open detail page of blog so I created Route Link with id But I have no idea How can I access it from url ? or How can I retrieve id passed in url ?

App.js


class App extends React.Component {
   render() {
      return (
         <div>
            ...
            <Route path='/blog-detail/:id' element={<BlogDetail/>} />
            ...
         </div>
      )
   }
}

function Blogs() {
   return (
         <div>

             {
               blogs.map(blog => 
              <div>
                   {blog.title}

                   <Link to={`/blog-detail/:${blog.id}`}>Open Blog</Link>
              </div>
             }

         </div>
   )
}


// Trying to access id passed in this component
function BlogDetail() {
   return (
         <div>

             Will display blog detail data from Backend by id


         </div>
   )
}

I have tried many times But it is still not working.

  • I could easily access by using window.location.href and slice after / But I think that would not efficient.

  • I can also pass state={{ id: blog_id }} using Link and access through useLocation But What if user doesn't click from Blog Component and input directly from browser.

Any help would be much Appreciated. Thank You in Advance

user19652801
  • 31
  • 1
  • 6
  • Does this answer your question? [How to pass id in Route React](https://stackoverflow.com/questions/72004170/how-to-pass-id-in-route-react) – Singh Aug 29 '22 at 09:01

3 Answers3

2

It should work like this:

import {useParams} from 'react-router-dom';

const params = useParams();
console.log(params); // {id: '1'}

Also there are more info here : How to pass id in Route React

Singh
  • 783
  • 1
  • 6
  • 24
1

You can use the useParamHook to get the parameter at the end of the route

const {id} = useParams();

This should help you get the id at the end of the route

rehkmansa
  • 57
  • 4
1

You can re-write BlogDeatils component as below:

import { useParams } from "react-router-dom";
....

function BlogDetail() {
    const { id } = useParams();


    return (
          <div>

            Blog id is {id}
 
          </div>
    )
 }
Arman
  • 641
  • 4
  • 12