There are two primary ways to style React components
style
propclassName
propBefore we get into those, you need to know something about 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 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' }} />
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;}
Quick Links
Legal Stuff
Social Media