Home > Back-end >  How to jump to the detail page when I click the img?
How to jump to the detail page when I click the img?

Time:10-25

I call the API to get all the images and render them on the page. Then I want to click on an image to navigate to a new page which can show the attributes of the clicked image like src, id, name, etc.

Here is the part of my code

function CustomContent() {
  const [customContent, setCustomContentResults] = useState([])
  const fetchData = async() => {...}

  useEffect(...)

  const handleClick=(post)=>{
 
  }
  const content = customContent?.map(post => {
    return <li key={post.id}>
      <div>
        <img alt="" src={post.src.medium} onClick={() => handleClick(post)}></img>
      </div>
     </li>
  })
  return (
    <div >
        <ul>
            {content}
        </ul>
    </div>
  )
}

How to write the handleClick function? And in the detail.jsx, how to get the post data?

CodePudding user response:

You should store post on localStorage, go to a new page and display it. But it's a bad practice.

Please go to "/post/:id" page. And need to reload post info with postId from params.

CodePudding user response:

use query string in URL to relay params

CodePudding user response:

First, you need add the router like this:

<Route path="/" element={<Layout />}>
  <Route
    path="detail/:id/"
    element={<DetailImage/>}
  />
</Route>

And add this to your component:

const content = customContent?.map(post => {
    return <li key={post.id}>
      <Link to="/detail/post.id>
        <img alt="" src={post.src.medium} ></img>
      </Link>
     </li>
  })

Finally, you need create DetailImage Component to show detail of image, and call API with useEffect have dependency is id

  • Related