How do I change the button color on click?

Viewed 525

I am using javascript and react-js to try to change the color of the "exclude" button when I click on it from white to red. If I click it again I want it to change back to white. I am doing this in the button tag and trying to use useState. I included the app.js file and app.css file. I can not get it to work. Please help!

function App() {
  const classes = useStyles()

  const [prev, changeColor] = useState(1)

  return (
    <div className="App">
      <header className="App-header">
        <Box
          sx={{
            display: 'grid',
            gap: 1,
            gridTemplateColumns: 'repeat(2, 1fr)',
            gridTemplateRows: 'auto',
            gridTemplateAreas: `"header header header header"
      "main main . sidebar"
      "footer footer footer footer"`
          }}
        >
          <Grid container spacing={12}>
            <Grid item md={12}>
              <Paper className=" "> Tag </Paper>
            </Grid>

            <Grid item xs={6} md={8}>
              <Box
                className={clsx(classes.containerBox, classes.containerBox)}
              ></Box>

              <Button
                id="excluded"
                onClick={() => changeColor(prev => (prev === 1 ? 0 : 1))}
                href="# "
                variant="contained"
                size="medium"
                style={{
                  fontSize: 20
                  //backgroundColor: bg ===1 ? "white" : "red"
                }}
                color="tertiary"
              >
                Exclude
              </Button>
            </Grid>
          </Grid>
        </Box>
      </header>
    </div>
  )
}

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

button {
  padding: 10px 20px;
  margin: 5px;
  background-color: grey;
  border-radius: 5px;
}

3 Answers

It is not changing because you are just assigning the value to prev not using the prev value.

And in onClick you can do like this,

onClick = {() => changeColor(!prev)}

and in style, use prev state variable

style = {{
       fontSize: 20,
       backgroundColor: prev === 1 ? "white" : "red"
}}

useEffect is a function to watch rerenders in your page. So when you use the function changeColor the page rerenders so you can edit your App.js to this

import React, {useEffect,useState} from 'react';

function App() {
 const classes = useStyles();

 const [prev, changeColor] = useState(1);

 useEffect(() => {
   if (prev === 0) {
     document.getElementById('excluded').classList.remove('color2');
     document.getElementById('excluded').classList.add('color1');
   } else {
     document.getElementById('excluded').classList.remove('color1');
     document.getElementById('excluded').classList.add('color2');
   }
 }, [prev]) // the state you are watching to change

 return (
   <div className="App">

     <header className="App-header">
     <Box
     sx={{
       display: 'grid',
       gap: 1,
       gridTemplateColumns: 'repeat(2, 1fr)',
       gridTemplateRows: 'auto',
       gridTemplateAreas:  `"header header header header"
"main main . sidebar"
"footer footer footer footer"`,
     }}
   >


     <Grid container spacing = {12}>

     <Grid item md = {12}>
     <Paper className = " "> Tag </Paper>

     </Grid>

           <Grid item xs = {6} md = {8}>


         <Box className = {clsx(classes.containerBox, classes.containerBox)}>

         </Box>

         <Button
         id = "excluded"
         onClick = { () => changeColor(prev => prev === 1 ? 0 : 1)}
         class="color2"
         href = '# '
         variant = "contained"

         size = "medium"
         style = {{
           fontSize: 20,
           //backgroundColor: bg ===1 ? "white" : "red"
         }}
           color = "tertiary">
           Exclude

         </Button>

         </Grid>

         </Grid>

or you can just add a function to change color onClick.

function App() {
 const classes = useStyles();

 const changeColor = (e) => {
   if (e.target.classList.contains('color2') {
     e.target.classList.remove('color2');
     e.target.classList.remove('color1');
   } else {
     e.target.classList.remove('color1');
     e.target.classList.remove('color2');
   }
 }
 
 return (
   <div className="App">

     <header className="App-header">
     <Box
     sx={{
       display: 'grid',
       gap: 1,
       gridTemplateColumns: 'repeat(2, 1fr)',
       gridTemplateRows: 'auto',
       gridTemplateAreas:  `"header header header header"
"main main . sidebar"
"footer footer footer footer"`,
     }}
   >


     <Grid container spacing = {12}>

     <Grid item md = {12}>
     <Paper className = " "> Tag </Paper>

     </Grid>

           <Grid item xs = {6} md = {8}>


         <Box className = {clsx(classes.containerBox, classes.containerBox)}>

         </Box>

         <Button
         id = "excluded"
         onClick = {changeColor}
         href = '# '
         class = "class2"
         variant = "contained"

         size = "medium"
         style = {{
           fontSize: 20,
           //backgroundColor: bg ===1 ? "white" : "red"
         }}
           color = "tertiary">
           Exclude

         </Button>

         </Grid>

         </Grid>

You can take several approaches here. Please review the core concepts from JS and from React as well.

import React from "react";
import "./styles.css";

const App = () => {
  const [color, setColor] = React.useState("red");
  return (
    <div className="App">
      <button
        style={{ backgroundColor: color }}
        onClick={() => {
          setColor(color === "red" ? "blue" : "red");
        }}
      >
        Click me
      </button>
    </div>
  );
};

export default App;

codesandbox

Related