skip to Main Content

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


  1. 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 the src property:

    Updated setImage():

    function setImage(e) {
      const src = e.currentTarget.querySelector('img').src
      setInsertImage(src)
    }
    
    Login or Signup to reply.
  2. To do this, you can change setImage() to have a parameter accepting the source, so that you can have the selected image show up:

    function App() {
      const [insertImage, setInsertImage] = useState("/images/camaro.jpg");
    
      function setImage(src) {
        setInsertImage(src);
      }
    
      return (
        <>
          <div className="w-full">
            <img src={insertImage} className="h-full w-full"></img>
          </div>
          <div className="w-96" onClick={() => setImage("/images/mclaren.jpg")}>
            <img
              src="/images/mclaren.jpg"
              className="transition-opacity delay-75 hover:opacity-70 cursor-pointer active:scale-95"
            ></img>
          </div>
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search