Home > Mobile >  Trying to pass an object to anothe page on react
Trying to pass an object to anothe page on react

Time:03-26

I am trying to make a blog page, where when you select a link from the home page it gives you a detailed page (much like opening a product detail page from a page of products). I am struggling to pass each blog object to the new details page to then display this information. I have tried passing through props and Links but everything I have tried has come back undefined.

App.js - containing routes to the different pages:

<div className="App">

  <NavBar/>
  <Router>
    <Routes>
      <Route path="/" exact element={<BlogPosts/>} /> 
      <Route path="/detail/:id" exact element={<BlogDetails/>} />
    </Routes>
  </Router>
</div>

BlogPosts which is the home page displaying the blogs. It maps through all the blogs to display them.

  <div>
  <div className="BlogPosts">

    {loader === false && (data.map((blog) => (
   
    <div className="BlogContainer" key={blog.id}>

        <img className="BlogImage" src={blog.image} alt={blog.title}/>

        <div className="BlogTextContainer">
            <h1 className="BlogTitle">{blog.title}</h1>
            <h2 className="BlogDate">{blog.date}</h2> 
            <p className="BlogSummary">{blog.summary}</p>


                      
            <Link to={{
              pathname: `/detail/${blog.id}`, 
              state: {
                blogTitle: blog.title,
                blogDate: blog.date,
              },
              }}
              >
            View {blog.title}
            </Link>

            
            
        </div>

    </div>
    )))}

  </div>
  </div> 

The BlogDetails page which is where I would like to display the data

function BlogDetails( ) {

return (
    <div>
        Display 
    </div>
)

}

All help is appreciated!!!

CodePudding user response:

You can use the useLocation hook

In BlogPosts component your Link should be:

<Link 
  to={`/detail/${blog.id}`} 
  state={{  
    blogTitle: blog.title, 
    blogDate: blog.date
  }}>

And in BlogDetails component you make use of that useLocation:

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

const BlogDetails= () => {
  const { state } = useLocation(); // Here we you destructuring, so you do not have to display values everywhere doing location.state
  console.log(state); // so you can see your state
  return (
    <>
      <p>{state.blogTitle}</p>
      <p>{state.blogDate}</p>
    </>
  );
};
export default BlogDetails;
  • Related