React styling
If we know how to render HTML with our React apps (with or without JSX), the next thing we want to know is how to style those DOM elements!
Let's also assume that we have used this process to React create apps from scratch in order to:
- Create a CSS file
- Import the CSS file in our React JS file
We will also look at how we can add styling inside the JavaScript!
Creating the CSS file
With this method, we use stylesheets like how we (mostly) did with HTML-only pages. This allows for a nice separation of concerns.
It allows for someone who does not know React (but knows CSS) to edit the CSS to their liking. React developers, on the other hand, can concentrate on programming without all the distracting snippets of style!
Suppose we have an App.css file:
/* src/App.css */
.myApp {
background-color: black;
color: white;
}
.myApp p {
color: green;
}
Importing the CSS file
In our React App.jsx file, we would just import it:
/* src/App.jsx */
import './App.css'
function App() {
return (
<div className="myApp">
<h1>White text on a black background!</h1>
<p>This paragraph has green text!</p>
</div>
)
}
With the import in place, this allows the App to:
- use the class names from the CSS in each React component's className
- allow selectors in CSS and have them function in the React component
Note that we have to use the attribute name className in JSX because class is already a reserved keyword in JavaScript!
CSS-in-JSX
We could also use CSS-in-JSX if we wish to debug styles or, later, for conditional styling. This involves injecting CSS into JSX via style attributes:
function MyInputBox() {
const myStyle = {
backgroundColor: 'black',
color: 'white'
}
return (
<input type="text" style={myStyle} />
)
}
Note that:
- the JSX portion looks like adding in-line styles on an HTML page
- here we use a variable (CSS written as a JavaScript object)
- the object enumerates the style properties
- here we use a variable (CSS written as a JavaScript object)
We could even write the above like this:
function MyInputBox() {
return (
<input type="text" style={{
backgroundColor: 'black',
color: 'white'
}} />
)
}
Note how the style attribute of the input JSX tag has a double layer of curly braces! We can think of the entire object as a variable name! However, this can get messy with a lot of CSS attributes, so we should use this syntax only when working with one or two CSS attribute(s).