0

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

1
  • I’m voting to close this question because it is a code writing request. Commented Sep 22, 2021 at 7:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hello I have some question. When I'm adding a category, if I use "backgroundcolor" it's having a delay, the changes of the CSS applies when I click the 2nd button. but when it's using only "color: yellow" it changes every click.
hi I think background-color don't have a delay. can you share your code .
-1

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.

2 Comments

but when I tried that, all the button are changing. I'm wanting to only change the button I clicked.
That is why, I suggested to have component with internal state, that changes only for that button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.