Dev

By Carlos Santana on
Reading time: 3 minutes

ReactAndCSS-qFSNN.png

In the last post Structuring our React Application like a pro we learned how to organize our application in a better way, also we created our first component called Home.js in the post Creating our first React application. Now let's add some CSS to our Home component and see how the styles work in React.

In React, a good practice is to have the style file in the same directory as the component. If you have worked with other languages such as PHP, Node or Ruby probably you write your styles in a style.css file, and then you include it using a link tag in your layout.

React uses Webpack, which is the most popular module bundler at the moment. With Webpack, we can configure the way that we want to handle our styles (using CSS directly or by using a CSS preprocessor such as Sass, Stylus or Less), and with Webpack we can implement CSS modules. This is a powerful way to avoid the three main issues of CSS:

  • No more conflicts (unintentional CSS overwrites)
  • Explicit dependencies (styles per component)
  • No global scope

In the next posts, I'm going to write about Webpack, and I'll show you how to implement the CSS modules using Sass, Stylus or Less in your project.

Let's add some styles to our Home component

Once you created your Home component you need to create another file called Home.css in the same level of your Home.js file, and then we need to import it in our Home component:

Only members can see all the codes
You can Login or Sign Up

File: src/components/Home/Home.js

After that, we need to add some styles:

.Home {
  border: 1px solid blue;
}

.Home h1 {
  font-size: 36px;
  color: red;
}
File: src/components/Home/Home.css

If you run your site now you should see something like this:

HomeStyles-AcYhy.png

Inline styles

As you can see is really easy to connect a CSS file to a component, but sometimes is also useful to use inline styles. Basically, we need to define our styles in an object and pass it to the style property on the elements, for example:

import React, { Component } from 'react';
import './Home.css'; // <-- Here we import our CSS file

class Home extends Component {
  render() {
    return (
      <div className="Home">
        <h1>I'm Home Component</h1>

        <p
          style={{
            backgroundColor: 'white',
            color: 'green',
            border: '1px solid orange',
            height: 100
          }}
        >
          This is an inline styled paragraph
        </p>
      </div>
    );
  }
}

export default Home;

File: src/components/Home/Home.js

If you prefer you can create an object variable or constant and then just pass it to the style prop like this:

import React, { Component } from 'react';
import './Home.css'; // <-- Here we import our CSS file

class Home extends Component {
  render() {
    // Inline styles in an object
    const styles = {
      backgroundColor: 'white',
      color: 'green',
      border: '1px solid orange',
      height: 100
    };

    return (
      <div className="Home">
        <h1>I'm Home Component</h1>

        <p
          style={styles}
        >
          This is an inline styled paragraph
        </p>
      </div>
    );
  }
}

export default Home;

File: src/components/Home/Home.js

Probably you noticed that the height is defined as a number and I didn't add the pixel unit (px), this is a behavior of React, automatically converts the numbers to pixels so we don't need to take care of that, but if you prefer you can define the value as string and manually add the unit like this: height: '100px'.

You should see something like this:

HomeInlineStyles-2ZcN5.png

Where are the styles?

You're probably curious about where is the CSS code since we haven't imported a CSS file to our project directly (by using a <link> tag for example). Well, you will be surprised to see that the CSS code is actually being injected into our <head> tag using the <style> tag for each imported stylesheet. If you inspect your project with Chrome DevTools you will see something like this: 

Styles-JVZ5P.png

This behavior is because the style-loader which is a Webpack loader that is being used by default in our React application when we create it using create-react-app.

This starter kit is using by default the package called "react-scripts" and in order to modify the default Webpack configuration of your application, you need to eject the configuration in the terminal by using npm run eject or yarn eject, but in this post we will not see this just yet, in the next posts I'll show you how to do your own customized Webpack configuration.

There are more Webpack loaders to do different things, such as css-loader for CSS modules, sass-loader to implement Sass, stylus-loader to implement Stylus, less-loader for LessCSS and mini-css-extract-plugin to move the CSS code to a .css file instead of injecting it to the DOM (usually this is only used in production).

Remember you can buy my book React Cookbook on the Packt's official website most of the time they have very good discounts.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up