Pinky Promise
Pinky Promise

Reputation: 223

Add color on every button Click React js

Hello guys I currently have a buttons like category. I want that when I click a button it will have a color, and when I click it again it will turn to it's original color which is white. When I click 2 button both will have dark color, then click again to remove single color.

this is my div when I'm adding a the category id

<div className={classes.scrollMenu}>
    {categories.map((category) => {
      return (
        <>
          <Button
            key={category._id}
            className={classes.button}
            onClick={(e) => {
              let values = {
                price: [],
                category: [category._id],
              }
            }}
          >
            {category.name}
          </Button>
        </>
      )
    })}
  </div>

This is the image that when I click single button it will color one button.

enter image description here

Thank you

Upvotes: 0

Views: 727

Answers (2)

Rishab Vaigankar
Rishab Vaigankar

Reputation: 443

code Solution: https://codesandbox.io/s/stoic-meadow-y5cei?file=/src/App.js

App.js

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

export default function App() {
  let categories = ["one", "two", "three"];
  const [activeFilter, setActiveFilter] = useState(["one"]);

  const categoryOnClick = (category) => {
    activeFilter.includes(category)
      ? removeCategory(category)
      : setCategory(category);
  };
  const setCategory = (category) => {
    setActiveFilter([...activeFilter, category]);
  };
  const removeCategory = (category) => {
    const index = activeFilter.findIndex((cat) => cat === category);
    activeFilter.splice(index, 1);
    setActiveFilter([...activeFilter]);
  };
  return (
    <div className="chip-list my-3">
      {categories.map((category, index) => {
        return (
          <button
            key={index}
            className={`${activeFilter.includes(category) ? "active" : ""}`}
            onClick={() => categoryOnClick(category)}
          >
            <span>{category}</span>
          </button>
        );
      })}
    </div>
  );
}

css

.active {
  background-color: black;
  color: white;
}

check if this solution works for you

  • used useState hook to hold the state of buttons which you will select
  • .active class will apply to the button which is selected
  • On click of that button we will check if the button is already selected or not if selected removeCategory() function run
  • or if button is not selected then setCategory() function will run and it will update the state

if you need clarification please let me know thanks

Upvotes: 2

Nectos
Nectos

Reputation: 206

Few tips to start with:

  1. Fragment is unnecessary when wrapping single DOM element
  2. Inline function initialisation inside a render is a bad thing. On each new re-render, it allocates extra client memory to newly initialised function. That means, for every map object you will have that many functions, that gets newly created and referenced on each reload
  3. You can easily go with single line return statement of arrow function here. () => <hi> instead of () => { return <hi> }

As for solutions, there are quite a few ways to change button colour during execution. I will suggest the most simple (in my opinion) way to do it. Just have classname variable, then add subclass that will style button accordingly.

Example: By default it has class name of .button, after click you simply add styling and it ends up having .button .button--red, all is left to do, declaration in css.

.button {
   style button here
. . .

   add additional stylings here
. . .
   &.button--red { color: red }
}

As for how handler should look like, if that is what you asking. Button could be used in your new component let's say, named StyledButton or ColourfulButton that will have internal state to handle what kind of colour is represented.

Upvotes: -1

Related Questions