HomeAbout Me

React Fundamental 6: Styling

By Daniel Nguyen
Published in React JS
May 06, 2025
1 min read
React Fundamental 6: Styling

There are two primary ways to style React components

  1. Inline styles with the style prop
  2. Regular CSS with the className prop

Before we get into those, you need to know something about element properties and HTML attributes.

Element properties and HTML attributes

In HTML, you have elements and attributes. For example, the div element has a class attribute:

<div class="my-class"></div>

In JSX, you use the property className rather than the attribute name:

<div className="my-class" />

This applies to a number of other attributes as well. For example, for in HTML is htmlFor in DOM (and JSX). Others include tabindex and readonly (which are, respectively, tabIndex and readOnly in JSX).

Most differences between HTML attributes and JSX props are due to the fact that props are a reference to “properties” not “attributes”, so understanding the difference is handy!

Inline styles

Inline styles are set differently in JSX from HTML as a result of how they are applied to the DOM. In HTML, you’d pass a string of CSS, but you access it as an object in the DOM:

<div id="my-div" style="margin-top: 20px; background-color: blue;"></div>
<script>
const myDiv = document.getElementById('my-div')
console.log(myDiv.style.marginTop) // "20px"
console.log(myDiv.style.backgroundColor) // "blue"
</script>

As a result, in JSX, you pass an object of CSS rather than a string:

<div style={{ marginTop: 20, backgroundColor: 'blue' }} />

Class names

The most common mechanism for styling web applications is through the use of CSS and class names.

As mentioned earlier, in HTML, you apply a class name to an element with the class attribute. In JSX, you use the className prop:

<div className="my-class" />

Then you’ll load a CSS file onto the page:

<link rel="stylesheet" href="styles.css" />

And that can contain the styles for .my-class:

.my-class {
margin-top: 20px;
background-color: blue;
}

Tags

#ReactFundamental

Share

Previous Article
React Fundamental 5: TypeScript

Table Of Contents

1
Element properties and HTML attributes
2
Inline styles
3
Class names

Related Posts

React Fundamental Section 10: Rendering Arrays
May 10, 2025
1 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media