0

In this react.js code I should read button’s label from “categorylist”. When I click on a button ,the color changed for all buttons. How can I change the color of each button by clicking on each one seperatly? Here is my code:

export default function CategoryPicker() {

const categorylist = [ { label: "Fact", id: 0, }, { label: "Event", id: 1, }, { label: "People", id: 2, }, { label: "Secure", id: 3, }, ]; const [clsitemchanged, setclsitemchanged] = useState("blue");

return ( Select a category

  <style>{`
    .blue {color: rgb(59,130,246);  border: 2px solid rgb(59,130,246); background-color:white; padding:12px 15px; inline-size:80px; border-radius: 9999px; margin-inline-start:3px;}
    .white {color: white; border: 2px solid rgb(59,130,246); background-color:rgb(59,130,246); padding:12px 15px; inline-size:80px; border-radius: 9999px; margin-inline-start:3px;}
  `}</style>
  {categorylist.map((currentElement) => {
    return (
      <button
        className={clsitemchanged}
        key={currentElement.id}
        onClick={() =>
          setclsitemchanged((ctr) => (ctr === "blue" ? "white" : "blue"))
        }
      >
        {currentElement.label}
      </button>
    );
  })}
 
</div>

); }

1 Answer 1

1

You need either array of changed items or separate component for button, that remembers its state.

return
  {categorylist.map((currentElement) => {
    return (
      <button
        className={clsitemchanged[id]}
        key={currentElement.id}
        onClick={() =>
          setclsitemchanged((ctr) => ({...ctr, [currentElement.id]: (ctr[currentElement.id]==="blue" ? "white" : "blue")}))
        }
      >
        {currentElement.label}
      </button>
    );
  })}

or separate component:

const MyButton = ({children})=>{
const [clsitemchanged, setclsitemchanged] = useState("white")
<button
        className={clsitemchanged}
        onClick={() =>
          setclsitemchanged((ctr) => (ctr==="blue" ? "white" : "blue"))
        }
      >
       {children}
      </button>
}

 {categorylist.map((currentElement) => {
    return (
      <MyButton   
        key={currentElement.id}>
        {currentElement.label}
      </MyButton>
    );
  })}
Sign up to request clarification or add additional context in comments.

Comments

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.