Adding Styles to React Components with CSS or Inline Styles

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

There are two main (default) ways to add styles to React components:

First, just normal CSS classes can be added to react components by setting a className attribute:

<p className='big-text'>BIG</p>

(It's called className instead of class because "class" is a reserved keyword in javascript)

Second, "inline styles can be added as javascript objects to the style attribute of a component:

<p style={{ fontSize: 20, color: 'blue' }}>Blue</p>

Notice that the "double curly braces" represent a javascript object being created inside of JSX, and also that the css attributes are camel cased.

Chris Achard: [0:00] There are two built-in ways to use CSS inside of React. The first is to use regular style sheets. Let's go to styles.css and make a new style called big-text. This is really just a regular CSS file.

[0:12] We can say that our font-size might be 40 pixels. Let's save that and go back to index. Now, we can make a new function component. We'll call this NormalCSS.

[0:24] From that, we're going to return in paragraph tag and we can say BIG. To set the class, normally we would set class equals HTML. The problem is class is reserved keyword in JavaScript.

[0:35] We're going to say className and then that can be the string big-text which we'll link it to proper style. Let's render NormalCSS as a custom component here. Then when we save, we get some BIG text.

[0:50] The second method is to use what's called inline styles. We make a new function called InlineStyle. From that, we're also going to return a paragraph and in here, we'll make some Blue Text.

[1:03] To make the style here, we're going to pass a style attribute and instead of taking a string that takes some JavaScript. Inside of that JavaScript, we're going to use another set of curly braces to make a JavaScript object.

[1:16] We have double curlies here. Inside of the style, we can set fontSize, for example, to 20. Now, notice that this is camelCase and not dashes like it is in regular CSS. It's camelCase because this is JavaScript we're writing now.

[1:30] We can say fontSize 20 and we might say the color is going to be 0000ff. Also notice we put the color inside of a string here because since this is JavaScript, we can't just use the pound sign. Now we can render InlineStyle.

[1:48] When we save that, we get some Blue Text as well. If this double curly braces confuses you, then you can do it like this as well. We can say that our const, our style is going to equal a new object with fontSize 20 and a color. Now, instead of declaring it down here, we can say that our style equals the JavaScript value of this style object we just made.

[2:14] If we save that, we get the same result. All we did was take this and cut it and paste it in here. That's why we get the double curlies.