user11877521
user11877521

Reputation: 331

Change color of button with onClick listener

I want to change the color of a button when I click on it. And if I click on another button, its color should be changed and previous button's color should be removed.

Here is the code.

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

function App() {
  const [style, setStyle] = useState(null);

  function applyStyles() {
    setStyle({
      backgroundColor: "green",
    });
  }
  return (
    <div>
      <button onClick={applyStyles}>1</button>
      <button onClick={applyStyles}>2</button>
      <button onClick={applyStyles}>3</button>
    </div>
  );
}

export default App;

Upvotes: 1

Views: 450

Answers (2)

Arifur Rahaman
Arifur Rahaman

Reputation: 574

You just need to store the inner text of the button in a state to detect which button has clicked and then style the button conditionally.

The working code is given.

import React, { useState } from "react";
    
    function App() {
      const [clicked, setClicked] = useState(null);
    
      const handleClick = (e) => {
        setClicked(e.target.innerText);
      };
      const buttons = ["1", "2", "3"];
      return (
        <div>
          {buttons.map((button) => (
            <button
              onClick={handleClick}
              style={{ background: clicked === `${button}` ? "green" : null }}
            >
              {button}
            </button>
          ))}
        </div>
      );
    }
    
    export default App;

codesandbox link: https://codesandbox.io/s/sleepy-rain-mwb929?file=/src/App.js

Upvotes: 1

KcH
KcH

Reputation: 3502

Not an efficient answer, but it does the job 😉

Nothing complex, easy to understand, lemme know if you have any doubt

const {useState} = React;

function App() {
  const [selected, setSelected] = useState(null);

  function applyStyles(e) {
    setSelected(e.target.value);
  }
  return (
    <div>
      <button value="1" className ={selected === "1" ? 'bg' : ""} onClick={applyStyles}>1</button>
      <button value="2" className ={selected === "2" ? 'bg' : ""} onClick={applyStyles}>2</button>
      <button value="3" className ={selected === "3" ? 'bg' : ""} onClick={applyStyles}>3</button>
    </div>
  );
}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
.bg{
      background-color : green;
    }
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Upvotes: 1

Related Questions