Gido
Gido

Reputation: 113

How to change image on button click with React Hooks?

I am learning React and I want to make two buttons: White and Black, that change images to white t-shirt and black t-shirt.

My goal is to achieve this with React Hooks.

import React, { useState, useEffect } from "react";
// import Black from "../../assets/black.jpg";
// import White from "../../assets/white.jpg";
import "./Shirts.css";

function Shirts() {
  const [white, setWhite] = useState(false);
  const [black, setBlack] = useState(true);

  const whiteImage = require(`../../assets/white.jpg`);
  const blackImage = require(`../../assets/black.jpg`);

  function changeToWhite() {
    console.log(setWhite(whiteImage));
  }

  function changeToBlack() {
    console.log(setBlack(blackImage));
  }

  // useEffect(() => {
  //   setWhite(white);
  // }, white);

  return (
    <div>
      <div className="Shirts">
        <img alt="T-Shirt" className="White" src={white} />
        <img alt="T-Shirt" className="Black" src={black} />
      </div>
      <div className="ColorPicker">
        <button className="WhiteB" onClick={changeToWhite}>
          <p className="WhiteT">
            W<br />
            H<br />
            I<br />
            T<br />E
          </p>
        </button>
        <button className="BlackB" onClick={changeToBlack}>
          <p className="BlackT">
            B<br />
            L<br />
            A<br />
            C<br />K
          </p>
        </button>
      </div>
    </div>
  );
}

export default Shirts;

What I achieved is they load on the first click but then they stop working.

Upvotes: 3

Views: 9532

Answers (1)

Dupocas
Dupocas

Reputation: 21297

First import both images:

const white = require('./images/white.png')
const black = require('./images/black.png')
const shirts = { white, black }

Now bind the selected T-Shirt to a state's property and pass it as src:

const Shirts = () =>{
    const [selected, setSelected] = useState(shirts.white)

   return(
       <>
           <img src={selected} alt='shirt' />
           <button onClick={() => setSelected(shirts.black)}> Click</button>
       </>
   )
}

Upvotes: 7

Related Questions