I’m building a product display component where the selected image is displayed as the main one. How do I get the source of each image in the useState? Should I pass it as a parameter to the function? I’m new to React so help would be greatly appreciated.
import { useState } from "react";
function App() {
const [insertImage, setInsertImage] = useState("/images/camaro.jpg");
function setImage() {
setInsertImage("SRC REQUIRED HERE");
}
return (
<div className="flex flex-col gap-3 max-w-3xl m-auto">
<div className="w-full">
<img src={insertImage} className="h-full w-full"></img>
</div>
<div className="flex gap-2">
<div className="w-96" onClick={setImage}>
<img
src="/images/camaro.jpg"
className="transition-opacity delay-75 hover:opacity-70 cursor-pointer active:scale-95"
></img>
</div>
<div className="w-96" onClick={setImage}>
<img
src="/images/mclaren.jpg"
className="transition-opacity delay-75 hover:opacity-70 cursor-pointer active:scale-95"
></img>
</div>
<div className="w-96" onClick={setImage}>
<img
src="/images/gtr.jpg"
className="transition-opacity delay-75 hover:opacity-70 cursor-pointer active:scale-95"
></img>
</div>
<div className="w-96" onClick={setImage}>
<img
src="/images/mclaren.jpg"
className="transition-opacity delay-75 hover:opacity-70 cursor-pointer active:scale-95"
></img>
</div>
</div>
</div>
);
}
export default App;
2
Answers
You can access the wrapper element via the click event using
currentTarget
(MDN Docs). From there, you can search for the contained image using a query selector (MDN Docs), and then read thesrc
property:Updated
setImage()
:To do this, you can change
setImage()
to have a parameter accepting the source, so that you can have the selected image show up: