Andrew
Andrew

Reputation: 622

How to change color button onclick react.js

I work with buttons, and on click i need to change color button.

I have two button: favorite and stats, and onclick i need to change to custom color, for ex favorite is orange, stats blue.

How i can change color onclick?

<div className={classes.fotter_button}>
                    <button>
                      <FontAwesomeIcon
                        icon={faStar}
                        aria-hidden="true"
                      />
                    </button>
                    <button>
                      <FontAwesomeIcon
                        icon={faChartBar}
                        aria-hidden="true"
                      />
                    </button>
                  </div>

Upvotes: 1

Views: 5594

Answers (2)

le123
le123

Reputation: 180

const [favorite,setFavorite]=useState(false)
const [stats,setStats]=useState(false)

<div className={classes.fotter_button}>
                <button onClick={()=>{setFavorite(true)}} style={{backgroundColor:favorite==true?"orange":""}}>
                  <FontAwesomeIcon
                    icon={faStar}
                    aria-hidden="true"
                  />
                </button>
                <button onClick={()=>{setStats(true)}} style={{backgroundColor:stats==true?"blue":""}}>
                  <FontAwesomeIcon
                    icon={faChartBar}
                    aria-hidden="true"
                  />
                </button>
              </div>

Upvotes: 2

Alan
Alan

Reputation: 46903

One way is to add state variable in your component, and use a function to change the state variable between two values (true, false). Apply the button styling based on the value of the state variable.

const MyToggleButton = () => {
 const [toggle, setToggle] = React.useState(false);
 const toggleButton = () => setToggle(!toggle);
 
 return (
  <>
    <button style={{backgroundColor: toggle ? '#FFF' : '#000'}} onClick={toggleButton}>Click Me</button>
  </>
 );
}

My example is pretty generic; if possible consider using a state variable that more aptly describes your buttons two states.

Upvotes: 2

Related Questions