React JS- Multiple Buttons


I’m trying to make multiple toggles buttons, and whenever the user clicks on any one of them, then I want it to become a bit darker. So, that user knows which one they’ve clicked.



Images of What I want to make After CLick

Img1 Img1


Img2: Img2


Img3 Img3



Requirements:

1.I want to enforce at least one button to be active with useState

2.I want to do this in React with Pure CSS and JS only. No external Packages.


Here’s sample code I’ve written. CODE:

import React, { useState } from "react";
import "./styles.css";

  // ${({ active }) => active && `opacity: 1;`}

export default function App() {
  const [active, setActive] = useState("first");

  return (
    <>
    <div className="App"> 
    <button className="button" active={active === "first"} onClick={() => {setActive("first"); }} >first</button>
    <button className="button" active={active === "Second"} onClick={() => {setActive("Second"); }} >Second</button>
    <button className="button" active={active === "Third"} onClick={() => {setActive("Third"); }} >Third</button>
      </div>
    </>
  );
}

Now, How do I make an OnClick function that holds the after Click? functionality?

I hope I explained my requirements very well

Answer

You can do it like this:

<button
  className={`button ${active === "first" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("first");
  }}
>
  first
</button>
<button
  className={`button ${active === "Second" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("Second");
  }}
>
  Second
</button>
<button
  className={`button ${active === "Third" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("Third");
  }}
>
  Third
</button>

And then in you css file:

.activeButton {
  background-color: red;
}