So there are 4 buttons in the component called Buttons. When they are pressed, they will be counter , which means the number will be incremented by one. When the number changes, the color should also change. I couldn't do the color change. The increment is working.
import { useState } from "react";
import "./App.css";
import Buttons from "./components/Buttons";
import Counter from "./components/Counter";
function App() {
const [counter, setCounter] = useState(0);
const [counterColor, setcounterColor] = useState("");
const changeCounter = (n) => {
return setCounter(n 1);
};
const arr = ["red", "green", "blue", "yellow"];
const changeColor = () => {
return setcounterColor(arr[0 1]);
};
console.log(counter);
return (
<div className="App">
<Counter
counter={counter}
clazz={counterColor}
/>
<Buttons
changeCounter={() => changeCounter(counter)}
changeColor={changeColor}
/>
</div>
);
}
export default App;
function Buttons({ changeCounter, changeCounterColor }) {
return (
<div>
<button onClick={(changeCounter, changeCounterColor)}>Click</button>{" "}
<button onClick={changeCounter}>Click</button> <button onClick={changeCounter}>Click</button>{" "}
<button onClick={changeCounter}>Click</button>{" "}
</div>
);
}
export default Buttons;
CodePudding user response:
If you want to call changeCounter
and changeCounterColor
after one click on the button, you could do it like so:
<button
onClick={() => {
changeCounter(1);
changeCounterColor(1);
}}
>
Click
</button>
To have your color change with the counter, change changeCouterColor
to:
const changeColor = (n) => {
return setcounterColor(arr[n-1]);
};