How to set Text color in React


Borislav Hadzhiev

Last updated: Apr 19, 2022


Check out my new book

Set Text color in React #

Use inline styles to set the text color of an element in React.js, e.g. <span style={{color: 'green'}}>colorful</span>. The text color will only be applied to the element to which it was added and its children.

const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Some{' '} <span style={{color: 'white', backgroundColor: 'lime'}}>colorful</span>{' '} text </p> </div> ); }; export default App;

react style text color

We used inline styles to change the text color of an element.

Notice that multi-word properties are camelCased when specified as inline styles.

The first set of curly braces in the inline style marks the beginning of an expression, and the second set of curly braces is the object containing styles and values.

The changed text color is only going to be applied to the span element.

If you need to do this often, you can extract the span element into a component which renders its children.

function ColorfulText({children}) { return <span style={{color: 'green'}}>{children}</span>; } const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Some <ColorfulText>colorful</ColorfulText> text </p> </div> ); }; export default App;

Whatever we pass between the opening and closing tags of the ColorfulText component will have the specific text color applied.

An alternative solution is to define a class in a global css file.

.red-text { color: red; }

And here is how we would import the App.css file and use the red-text class.

import './App.css'; const App = () => { return ( <div> <p style={{fontSize: '2rem'}}> Some <span className="red-text">colorful</span> text </p> </div> ); }; export default App;

set text color global css

This approach enables us to reuse commonly used styles by defining them in a global css file.

It's a best practice to import your global css files in your index.js file because then they wouldn't only get loaded when certain component is mounted.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.