How to change button text color in react js?
June 01, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, I am going to show you. how to change button text color in react js with code example.
In this article, we will create a simple button text color in React.js just like you would create in a normal HTML project.
To change the style of a button on click with React, we can set the className
prop to an object with styles controlled by states.
Let’s look at the following example to understand how it basically works:
APP.js
import React, { useState } from "react";
export default function App() {
const [cls, setCls] = useState("green");
return (
<>
<style>{`
.red {color: red}
.green {color: green}
`}</style>
<button
className={cls}
onClick={() => setCls((cls) => (cls === "red" ? "green" : "red"))}
>
Button
</button>
</>
);
}
We have the red and green classes with the color CSS property set to red and green respectively.
Then we set the className
prop to the cls
state to let us control which class to set the button to.
Next, we set the onClick
prop to a function that calls setCls
with a function that returns the class we want to set for the button.
As a result, when we click the button, we see the text of the button toggle between green and red
Step to Run Application: Run the application using the following command
from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/,
you will see the following output:
Check the output of the above code example.
All the best 👍