Inline Styles in React
React is a JavaScript-based library that creates reusable components in our web applications. We can customize the functionality and the visual appearance of our components.
We can use these components as building blocks to make a robust, highly functional web application.
React applications are written in JSX, a templating language that resembles HTML but allows web developers to use JavaScript in the markup structure. JSX works similarly to HTML in many ways, but slight differences exist.
Like HTML, you can write inline styles in JSX, but there’s one big difference: the styles have to be represented as an object, not a simple string.
This article will explore the different ways to apply inline styles in React.
Inline Styles in React
Web developers have not yet settled which is the best way to style components in React. Some like to use preprocessors like SCSS, others like to stick with regular CSS, but there are differences even in this camp.
Some React developers like to keep all their styles in one CSS file, while others want separate stylesheets for each component. The disadvantage of using external stylesheets is that there’s a good chance you’ll eventually run out of unique and descriptive names for classes.
Luckily, you can apply inline styles directly to the components, so there is no need to create separate class names for them. Inline styles also solve the problem of simplicity.
React developers don’t have to look through long stylesheets to change the element’s style with inline styles. With inline styles, CSS and JavaScript are interconnected.
Uses of Inline Styles in React
As we previously mentioned, to apply inline styles in JSX, they must be written as an object. If you pass a JavaScript object (or any JavaScript expression) as a value to the style
attribute, it must be wrapped in curly braces.
Opening and closing curly braces are also used to define an object, so if you take a look at the simple definition of inline styles in React, it looks like double curly braces:
export default function App() {
return (
<div>
<h1 style={{color: "red"}}>Hello CodeSandbox</h1>
</div>
);
}
Add Conditions to Inline Styles in React
However, the curly braces {}
wrapped around the style
object allow us to do more than pass a JavaScript object. We can also use ternary operations to apply styles based on a state value and allow users to change that value.
The simplest example would be turning on/off the night mode. Let’s take a look at an example:
import { useState } from "react";
export default function App() {
const [nightmode, setNightMode] = useState(false);
return (
<div
style={{
backgroundColor: nightmode ? "black" : "white",
color: nightmode ? "white" : "black"
}}
>
<h1>Hello, Dear Users</h1>
<input
type="checkbox"
name="nightmode"
onChange={() => setNightMode(!nightmode)}
/>{" "}
Turn on night mode
</div>
);
}
You can check the demo on CodeSandbox and see how it works yourself.
This is a simple application with a div with text and a checkbox. Selecting and unselecting the checkbox makes the application switch back and forth between night mode and light mode.
We start by importing the useState()
hook, which is essential to update the state value based on the user’s input. Then we create two variables: nightmode
and setNightMode
.
The former will store the state variable itself, while the latter will be assigned an updater function by the useState
hook. Finally, we set a default value for the state variable to false
.
Then, we get to the style
object of the div
element, which has two properties: backgroundColor
and color
.
Before we proceed any further, note that the traditional name of the CSS property is background-color
, but in JavaScript, two words are pushed together, and it’s camel-cased. This is a convention for writing inline styles in React.
The values for these properties are ternary operators. Both check the value of the nightmode
variable.
If it’s true, then the backgroundColor
takes the value of black
; otherwise, the value will be white
. Since we set the state value to false
, the background color will be white by default.
Then we have the color
property, which sets the values so that they are opposite of the background to ensure that the text and background colors have a high degree of contrast.
The onChange
event handler flips the state value every time the user ticks and unticks the checkbox. With that, we have a simple example of how you can use inline styles to change the appearance of your element conditionally.
Object Reference as an Inline Style in React
In this case, our style
object is relatively simple, and it doesn’t interfere with the readability of the code. However, imagine if we had dozens of styles for the div
element.
If you write out all the styles, the code will take more space than the entirety of other elements. In that case, it would be wise to move the object outside of the return
statement and reference it.
Based on the above example, the code would look something like this:
import { useState } from "react";
export default function App() {
const [nightmode, setNightMode] = useState(false);
const divStyle = {
backgroundColor: nightmode ? "black" : "white",
color: nightmode ? "white" : "black"
}
return (
<div
style={divStyle}
>
<h1>Hello, Dear Users</h1>
<input
type="checkbox"
name="nightmode"
onChange={() => setNightMode(!nightmode)}
/>{" "}
Turn on night mode
</div>
);
}
This way, the JSX code looks much less cluttered.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn