Four Ways to Style React Components

The example component

Let’s start off with a sample header component that has no styling.

const Header = () => {
    return (
        <div>
            <h1>Welcome!</h1>
        </div>
  )
}

Method 1: Inline

React allows us to put stying directly into our components. Assume we have a component which display some user contact data

const Header = () => {
    return (
        <div>
            <h1 style={{ color: "red", fontSize: "50px" }}>Welcome!</h1>
        </div>
  )
}

Method 2: In the component Javascript file

This method keeps the stying in the same file as the component, but allows us to define it separately, reducing clutter within the actual component.

const Header = () => {
    return (
        <div>
            <h1 style={ headerStyle }>Welcome!</h1>
        </div>
  )
}

const headerStyle = {
  color: "red", 
  fontSize: "50px"
}

You may have noticed methods one and two do not use normal CSS names (eg, fontSize instead of font-size. Styles are specified as an object, where the key is the camelCased version of the CSS property name.

Method 3: Using an external CSS file

In this example we create a CSS file with the same name as the component, and reference that inside the JavaScript file.

Header.css

h1 {
    color: "red";
    font-size: "50px"
}
import './Header.css";

const Header = () => {
    return (
        <div>
            <h1 style={ headerStyle }>Welcome!</h1>
        </div>
  )
}

const headerStyle = {
  color: "red", 
  fontSize: "50px"
}

The CSS file can also be stored elsewhere (ie, outside of the components folder) and can be imported in the main App.js file. This is useful when we want to have global CSS properties which aren’t necessarily tied to a specific component.

Method 4: Using Bootstrap or another CSS framework

These can be installed using NPM, and imported in the main App.js file.

To install and save to the package.json run npm install bootstrap --save. Once installed it can be imported via

import 'bootstrap/dist/css/bootstrap.min.css'

At this point we can simply use Bootstrap classes inside our components.

const Header = () => {
    return (
        <div className="container">
            <h1 className="display-4">Welcome!</h1>
        </div>
  )
}

If you enjoyed this post consider sharing it on , , , or , and .