React styling
changing the look of what appears on the render
Last updated
changing the look of what appears on the render
Last updated
So, those with a more "vanilla" (HTML + CSS only) web development background might ask:
"How do we add CSS in React, then?"
We can do so in two ways: in-line and variable
We can inject CSS into our JSX elements using the style
attribute:
A few things to note with this way of adding styles:
it looks a lot like adding
styles actually bundle together as properties of a JavaScript object, rather than as separate attributes
we pass in the object (think of the entire object as a variable name!) into the style attribute
style properties use camelCase as opposed to kebab-case in regular CSS
When properties in the style object become too numerous (e.g. in addition to backgroundColor
and color
, we might also have margin
, padding
, border
, etc.), we can package the object into a variable before the return
statement:
(Now, it should become quite clear why the style
attribute had a set of nested curly braces!)
So, the entire style object gets assigned to a variable name and placed elsewhere in the code. This cleans up the contents of the return
statement, especially if the style properties become too numerous.
We can also use conditional rendering methods to output different styles depending on dynamic data:
In the above, the backgroundColor
is black and the (text) color
is white since the variable darkMode
is true. We also have a ternary operator on the padding
, which could be 30px with spaceyMode
or 10px without.