-1

Working on a react app and we have managed to figure out your classic search bar function for our cloudinary/mongoDB database. However we have a carousel of images on our homepage that corresponds with our search engine. We would like to figure out how to filter results based on which image you click, any ideas on where to start with this?

Been googling around and not managed come across anything useful yet, perhaps just pointing me in the right direction would be enough! Thank you.

1 Answers1

0

You can wrap the <img /> in a <button /> extract the imageId from the button's onClick and send it to the backend. The backend can do it's thing based on the imageId the front-end sends to it.

There are several other ways. Using custom attributes you don't even need the button. Just add a data-id attribute to the <img data-id={imageId} onClick={handleClick} /> by using const id = e.currentTarget.getAttribute("data-id") in the onClick function. But I would suggest using a button without any styles as it's better for accessibility.

Here is the answer that demonstrates how to use custom attributes and extract data from DOM elements.

const Component = () => {
  const handlClick = async (id) => {
    const result = await makeAPICall(id)
    // set the result in state and do whatever
  }

  return (
    <button onClick={(id) => handleClick(id)}>
      <img />
    </button>
  )
}

Tom Bombadil
  • 2,329
  • 1
  • 9
  • 20