Home > Software design >  In react, how can I deselect an element after it has been set as active with onClick?
In react, how can I deselect an element after it has been set as active with onClick?

Time:09-29

I have an image grid in react, with an onclick function that highlights the selected image. Clicking another image will change the active element but I'd like to be able to re-click the selected icon to deselect it and return the grid to default.

Here is my codesandbox and the script is below

import { useState, useRef, useEffect } from "react";
import "./App.css";
import { Data } from "./Data.js";
function App() {
  const scrollRef = useRef();

  useEffect(() => {
    const el = scrollRef.current;
    if (el) {
      const wheelListener = (e) => {
        e.preventDefault();
        el.scrollTo({
          left: el.scrollLeft   e.deltaY * 5,
          behavior: "smooth"
        });
      };
      el.addEventListener("wheel", wheelListener);
      return () => el.removeEventListener("wheel", wheelListener);
    }
  }, []);

  const [active, setActive] = useState(-1);
  const [active2, setActive2] = useState(false);

  return (
    <div ref={scrollRef} className="grid_container">
      {Data.map((prev, i) => {
        return (
          <div
            onClick={() => {
              setActive(i);
              setActive2(true);
              console.log(prev.Team);
            }}
            className={`${
              (active === i && "scale") || (active2 && "notScale")
            } card`}
            key={i}
          >
            <img src={prev.TeamBadge} alt="" />
          </div>
        );
      })}
    </div>
  );
}

export default App;

CodePudding user response:

You can set your state like that :

  setActive2(!active2);

CodePudding user response:

If I understand the problem correctly, I think this solves the problem, based on the codesandbox:

        onClick={() => {
          setActive(i);
          if (active === i) {
            setActive2(null);
            setActive(null);
          } else {
            setActive2(true);
          }
          console.log(i);
          console.log(prev.Team);
        }}

since every team has its unique number, the logic here is to check if the same number is in the state (if that makes sense). Let me know if this was you are looking for!

  • Related