HomeTutorsContact
ReactJS
How to style a React element?
Gulshan Saini
July 14, 2020
1 min

There are a lot of ways to style React elements using different libraries. In this tutorial, we will focus on only styling elements without any libraries.

We will kick off this tutorial with the following code that

  • imports React, ReactDOM and Babel
  • <script> tags that contain reactElement and ReactDOM.render method
  • has a root element with id of root, to render the React application

If you save the above code inside an HTML file and load in the browser, you should see text Hello World that is rendered by React.

Output

Let’s style the reactElement using following two ways

  1. Inline styles
  2. CSS class

Inline styles

Inline styles in React are defined as JavaScript objects with camelCased properties rather than a CSS string.

Example

Output

You can even extract the styles object as a variable and put it inside curly braces as follows

The output would be the same. Inline-styles work perfectly, however, if you have repetitive styles, it’s better to move, those styles, to an external CSS stylesheet.

Complete code inline styles

If you save the above code inside an HTML file and load in the browser, you should see text Hello World rendered with cyan background.

CSS class using external stylesheet

We can move the styles to the external stylesheet to clean up the React element and make the styles reusable. We can define a class in an external stylesheet and pass that class name in className attribute.

In React the atribute is className instead of class as class is reserved keyword in JavaScript.

We will move the inline styles defined in previous section to <head> element as follows

and, in the element we will refer the class name as follows

Complete code using external CSS

If you save the above code inside an HTML file and load in the browser, you should see text Hello World rendered with cyan background.

Tip: CSS classes can be added conditionally based on application state.

Outro

This tutorial shows two ways of styling the React element. We learned how to style an element using inline styles and external style sheets.


Tags

#react
Previous Article
How to create a React element?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to set dynamic inner text with React.createElement()?
July 19, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media