Setting inline Styles in React.js

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
6 min

banner

# Table of Contents

  1. Setting inline Styles in React.js
  2. Extracting the styles object into a variable
  3. Conditionally setting inline styles
  4. Interpolating expressions with a string when setting inline styles
  5. Using custom components to set inline styles
  6. Using an external stylesheet
  7. Insert a style tag in a React component
  8. Adding CSS inline

# Setting inline Styles in React.js

To set inline styles in React:

  1. Set the style prop on the element to an object.
  2. Set the specific CSS properties and values to style the element.
  3. For example, <div style={{backgroundColor: 'salmon'}}>.
App.js
const App = () => { const stylesObj = { backgroundColor: 'lime', color: 'white', }; const elementWidth = 150; return ( <div> {/* ๐Ÿ‘‡๏ธ Set inline styles directly */} <div style={{backgroundColor: 'salmon', color: 'white'}}> Some content </div> <br /> {/* ๐Ÿ‘‡๏ธ Set inline styles using an object variable */} <div style={stylesObj}>Some content</div> <br /> {/* ๐Ÿ‘‡๏ธ Set inline styles conditionally using a ternary */} <div style={{ backgroundColor: 'hi'.length === 2 ? 'violet' : 'mediumblue', color: 'hi'.length === 2 ? 'white' : 'mediumpurple', }} > Some content </div> <br /> {/* ๐Ÿ‘‡๏ธ Set inline styles interpolating a variable into a string */} <div style={{ width: `${elementWidth}px`, backgroundColor: 'salmon', color: 'white', }} > Some content </div> </div> ); }; export default App;

react set inline styles

The code for this article is available on GitHub

The code sample shows multiple ways to set inline styles on an element in React.js.

The first example sets the styles directly on the element.

App.js
<div style={{backgroundColor: 'salmon', color: 'white'}}> Some content </div>

Note that multi-word properties like background-color are camelCased when set on the style object.

The value of the style property is wrapped in 2 sets of curly braces.

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.

# Extracting the styles object into a variable

The second example extracts the styles object into a variable.

App.js
const App = () => { const stylesObj = { backgroundColor: 'lime', color: 'white', }; return ( <div> {/* ๐Ÿ‘‡๏ธ Set inline styles using an object variable */} <div style={stylesObj}>Some content</div> </div> ); }; export default App;
The code for this article is available on GitHub

You can use this approach when you have multiple elements that share the same styles.

# Conditionally setting inline styles

You can also conditionally set inline styles in React using the ternary operator.

App.js
import {useState} from 'react'; const App = () => { const [count, setCount] = useState(0); return ( <div> <h2 style={{ backgroundColor: count > 0 ? 'lime' : 'salmon', color: count > 0 ? 'white' : 'powderblue', }} > Count: {count} </h2> <h2 style={ count > 0 ? {backgroundColor: 'lime', color: 'white'} : {backgroundColor: 'salmon', color: 'powderblue'} } > Count: {count} </h2> <button onClick={() => setCount(current => current + 1)}> Increment </button> </div> ); }; export default App;

react set inline styles

The code for this article is available on GitHub

The first example shows how to use the ternary operator to check for a condition when setting the value of a specific CSS property in the element's styles.

App.js
<h2 style={{ backgroundColor: count > 0 ? 'lime' : 'salmon', color: count > 0 ? 'white' : 'powderblue', }} > Count: {count} </h2>

The ternary operator is very similar to an if/else statement.

If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.

In the first example, we check if the count variable stores a value greater than 0. If it does, we set the backgroundColor property to lime, otherwise we set it to salmon.

App.js
<h2 style={{ backgroundColor: count > 0 ? 'lime' : 'salmon', color: count > 0 ? 'white' : 'powderblue', }} > Count: {count} </h2>

You can imagine that the value before the colon is the if block and the value after the colon is the else block.

You can also use the ternary operator to conditionally set a value for the entire style prop.

App.js
<h2 style={ count > 0 ? {backgroundColor: 'lime', color: 'white'} : {backgroundColor: 'salmon', color: 'powderblue'} } > Count: {count} </h2>

When we use the style prop, we have 2 sets of curly braces. The outer set indicates to React that we have an expression that has to be evaluated.

The inner set of curly braces is the object of CSS properties and values.

If you have multiple properties whose values are determined by the same condition, you could use the ternary operator to return an entire object of properties and values.

However, you could also extract the condition into a variable and use the first approach.

App.js
const isGreaterThan0 = count > 0; // ... <h2 style={{ backgroundColor: isGreaterThan0 ? 'lime' : 'salmon', color: isGreaterThan0 ? 'white' : 'powderblue', }} > Count: {count} </h2>

# Interpolating expressions with a string when setting inline styles

You can also interpolate expressions or variables with a string when setting inline styles.

App.js
const App = () => { const elementWidth = 150; return ( <div> {/* ๐Ÿ‘‡๏ธ Set inline styles interpolating a variable into a string */} <div style={{ width: `${elementWidth}px`, backgroundColor: 'salmon', color: 'white', }} > Some content </div> </div> ); }; export default App;
The code for this article is available on GitHub

We used a template literal to concatenate a string and a variable when setting styles.

The width property of the div element is set to 150px.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

# Using custom components to set inline styles

A commonly used pattern in React is to extract wrapper components with predefined styles that render their children prop.

App.js
function BoldText({children}) { return <span style={{fontWeight: 'bold'}}>{children}</span>; } const App = () => { return ( <div> <p> Hello <BoldText>World</BoldText> </p> </div> ); }; export default App;

extract component for common styles

This is a very simple example, but the BoldText component sets some styles on an element and renders its children prop.

This approach is commonly used to define wrapper components with styles that are commonly reused.

I've also written a detailed guide on how to bold text in React.

# Using an external stylesheet

An alternative to writing inline styles in React is to write your styles in a file with a .css extension.

App.css
.bg-salmon { background-color: salmon; } .text-white { color: white; } .font-lg { font-size: 2rem; padding: 10px 10px; }

And here is how we would import and use the classes.

App.js
// ๐Ÿ‘‡๏ธ import your CSS file import './App.css'; const App = () => { return ( <div> <p className="bg-salmon text-white font-lg">hello world</p> </div> ); }; export default App;

style using a css file

The code for this article is available on GitHub

When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to run.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

If you need to change an element's style using a Ref in React, click on the link and follow the instructions.

# Insert a style tag in a React component

To insert a style tag in a React component, wrap your CSS in a template string in the style tag.

The expression between the curly braces will be evaluated and the styles will be added.

App.js
const App = () => { const styles = ` .my-h2 { padding: 25px; background-color: salmon; color: white; } `; return ( <div> <h2 className="my-h2">Hello world</h2> <style>{styles}</style> </div> ); }; export default App;

The expression between the curly braces in the style tag will be evaluated and the styles will be added.

react insert style tag

# Adding CSS inline

You can also inline the CSS directly in the style tag.

App.js
const App = () => { return ( <div> <h2 className="my-h2">Hello world</h2> <style>{` .my-h2 { padding: 25px; background-color: salmon; color: white; } `}</style> </div> ); }; export default App;
The code for this article is available on GitHub

The code snippet above achieves the same result.

Note that the styles we added with the style tag are not scoped to the App component.

Another component can use the my-h2 class as long as the App component is rendered.

If you need to set a global font family in React, click on the following link.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev