Last updated: Apr 7, 2024
Reading timeยท6 min
To set inline styles in React:
style
prop on the element to an object.<div style={{backgroundColor: 'salmon'}}>
.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;
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.
<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 second example extracts the styles object into a variable.
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;
You can use this approach when you have multiple elements that share the same styles.
You can also conditionally set inline styles in React using the ternary operator.
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;
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.
<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.
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
.
<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.
<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.
However, you could also extract the condition into a variable and use the first approach.
const isGreaterThan0 = count > 0; // ... <h2 style={{ backgroundColor: isGreaterThan0 ? 'lime' : 'salmon', color: isGreaterThan0 ? 'white' : 'powderblue', }} > Count: {count} </h2>
You can also interpolate expressions or variables with a string when setting inline styles.
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;
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
.
The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.
A commonly used pattern in React is to extract wrapper components with
predefined styles that render their children
prop.
function BoldText({children}) { return <span style={{fontWeight: 'bold'}}>{children}</span>; } const App = () => { return ( <div> <p> Hello <BoldText>World</BoldText> </p> </div> ); }; export default App;
This is a very simple example, but the BoldText
component sets some styles on
an element and renders its children
prop.
I've also written a detailed guide on how to bold text in React.
An alternative to writing inline styles in React is to write your styles in a
file with a .css
extension.
.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.
// ๐๏ธ 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;
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.
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.
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.
You can also inline the CSS directly in the style
tag.
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 snippet above achieves the same result.
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.
You can learn more about the related topics by checking out the following tutorials: