Inline Styling In React
Jun 18, 2019 • 7 Minute Read
Introduction
Cascading Style Sheets, commonly known as CSS, is a major building block of web development.
There is a famous saying, "It is the box, that helps to sell the jewelry", and the same is true with CSS. Although functionality is an important aspect in modern web development, how we present content is equally important.
With CSS, we can define the presentation of a document, the set of rules that control the formatting of an element on a webpage. By using CSS techniques, we can make webpages more appealing and efficient.
Before jumping in, let's discuss a bit about React. It's a popular JavaScript library for building user interfaces. It basically handles the view-layer of the application. The best part is that it allows you to break a component into smaller, reusable components. Instead of putting all the logic into a single file, writing smaller components has a better edge. By writing well-encapsulated components, we are essentially making a testable app with a good separation of concerns and maximum code reuse.
Ways of Defining CSS with React:
There are many ways of styling the React component, these are the common ones:
- Inline CSS
- CSS Stylesheet
- CSS Modules
- CSS in JS
I will not be going into the details and differences between each these because that mostly depends on the use case and application type, but I would say CSS in JS (especially Styled-Component) is a better (common) way of styling.
Inline CSS
Inline CSS means defining the CSS properties using a style attribute with an HTML tag or adding the styles directly to the element. With plain HTML, we assign a string value to style attribute. That string will contain CSS property value pairs; each property will be separated from each other by a semicolon. For an example of a basic page to show formatted "Hello World" is shown below:
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>
<body>
<p style="font-size: 20px; color:#4a54f1; text-align:center; padding-top:100px;">
Hello World!!!
</p>
</body>
</html>
Defining Inline Styles with React
Now we’ve come to the main discussion With React, we don't specify CSS the same way as we do with plain HTML. Before going into more detail, I would like to quickly remind you that we don't write HTML with React, we write JSX. What I mean by this is that JSX will get transpiled into React.createElement(....) and all the attributes will become the part of the props object.
In React, inline styles are not specified as a string. The style attribute accepts a JavaScript object with camelCased properties.
For example: margin-top -> marginTop , border-radius -> borderRadius , font-weight -> fontWeight , background-color -> backgroundColor
Below are the basic steps for defining inline CSS:
- Change the CSS property name to its camelCase version like "background-color" to "backgroundColor", "font-size" to "fontSize", etc.
- Create an object with all the CSS properties as keys and their CSS values.
- Assign that object to the style attribute.
We don't need to do any change to properties like "color", "border", "background", etc.
To get the same output formatted "Hello World", we need to write a React component in this way:
import React from 'react';
import ReactDOM from 'react-dom';
function HelloWorld() {
const styleObj = {
fontSize: 14,
color: "#4a54f1",
textAlign: "center",
paddingTop: "100px",
}
return(
<p style={styleObj}>Hello World!!!</p>
)
}
/*
Instead of creating a separate object, we can write it in this way also:
<p style={{ fontSize: 14, color: "#4a54f1", textAlign: "center", paddingTop: "100px" }}>Hello World!!!</p>
For better readability, define it separately.
*/
ReactDOM.render(<HelloWorld />, document.getElementById('app'));
If you look at the code above, you will notice that with fontSize, I did not use any unit and have just assigned a number and a string to paddingTop. And I did it on purpose. Basically, the idea is:
React will automatically append a "px" suffix to certain numeric inline style properties. If you want to use units other than "px", specify the value as a string with the desired unit. But there are some exceptions, few CSS properties are unitless, check the full list of unitless properties here.
Useful Scenarios
Now, let's assume we want to dynamically compute or modify a CSS property of a given item. For example, if we want to change the font color, toggle the display property/background image with some condition, change the width or height of an element, etc., then it’s easily achievable using the inline CSS.
Here’s another eExample, let’s assume we have a todo list. Each item can have a couple of states, it could be completed or, let's say, left to faith. To differentiate, we can highlight the pending items in red.
import React from 'react';
import ReactDOM from 'react-dom';
const todoList = [{ title: 'item 1', isDone: false }, { title: 'item 2', isDone: true }]
function TodoItem({ title, isDone }) {
return (
<div>
<p style={{ color: isDone? 'green': 'red' }}>{title}</p>
</div>
)
}
function Todo(props) {
const todoList = props.todoList.map(el => <TodoItem key={el.id} title={el.title} isDone={el.isDone} />)
return <div>{todoList}</div>
}
ReactDOM.render(<Todo todoList={todoList} />, document.getElementById('app'));
Disadvantages of Inline CSS
- Duplication of CSS properties
- CSS properties will be limited to a component scope only, so there is zero reusability
- We will not be able to utilize the full power of CSS, for example, no pseudo-classes, pseudo-element, media queries, keyframe animations, etc.
- It is hard to maintain or edit/update, and lot of inline CSS can reduce the code readability
- It hampers the performance, on each re-rendering the style object will be recomputed
Useful Links:
Details about JSX:
- Introducing JSX
- JSX In Depth Check this link for most common CSS properties and their camelCase equivalents:
- CSS Properties Reference React Doc Ref of Inline Styling:
- DOM Elements Use Babel Repl to check the transpiled code:
- Babel
Conclusion
I hope, this guide was helpful in understanding the basics of Inline CSS with React components and can serve as a roadmap for your journey.