How to Use CSS in JSX
In traditional web development, we typically separate HTML, CSS, and JavaScript files. However, React combines HTML (JSX) and JavaScript in a single file.
When styling React components, we have two main options:
- inline CSS
- external CSS.
Let’s explore how inline CSS works in React.
JSX represents objects as key-value pairs, similar to property names and their values. Always enclose values in quotation marks (" "
), just as you would in regular JavaScript objects.
When adding inline styles to JSX elements, we use double curly braces: the outer set represents a JavaScript expression, while the inner set defines the style object.
const App = () => {
return (
<>
<h1 style={ { color: "Red" } }>Hello World!</h1>
<p style={ { fontSize: "20px" } }>Here is some paragraph text</p>
</>
);
}
Looking at the style of the H1 tag in isolation we can see that it is indeed an object:
{
color: "Red"
}
In summary, use curly braces to add styles, structure them as key-value pairs, and always enclose the values in quotation marks (” ”).
Let us see now, how to use an external css file:
We simply create a .css file and import it in our .jsx file like this:
import './style.css'
/*
Your code here
*/