5 Ways to Style React Components in CRA (Create React App)

5 Ways to Style React Components in CRA (Create React App)

Styling in React is a piece of cake

#1. Plain CSS/SCSS

You can simply create a CSS / SCSS files anywhere inside your src directory in your CRA, simply import it in your components, and you are ready to use CSS / SCSS files in your React project. Note: For using SCSS in a CRA, you have to install a npm package called sass.

Let’s say your CSS / SCSS file name is App.css, here is how you can import it in your App.js component inside src folder:

// For CSS files
import './App.css';

// For SCSS files
import './App.scss';

#2. CSS/SCSS Modules

The biggest disadvantage of importing CSS / SCSS is that it applies all styles globally, which means your styles will not be unique to the component where it has been imported.

But React supports CSS / SCSS modules out of the box.

You just have to replace the extension .css or .scss with .module.css or .module.scss respectively and voilà your styles are unique to the component where it has been imported.

This is how you can import your component unique styles in your React Component:

import './App.module.css';

// For SCSS files
import './App.module.scss';

#3. Inline CSS

Similar to HTML inline CSS, you can write CSS on JSX elements as well, using style attributes. But in JSX, you have to pass your CSS properties, as a JS object inside the style attribute.

But the recommended way is to use classes instead of inline CSS, CSS classes are generally better for performance than inline styles.**

const MyComp = () => {
    return <div style={{ height: "20px" }]> My Div </div>
}

#4. CSS-in-JS:

You can be a bit smart and leverage inline CSS functionality to write your CSS inside the components as a JS object.

const MyComp = () => {
    return <div style={styles.div}> My Div </div>
}

const styles = {
    div: {
        color: "red"
    }
}

#5. Styled Components:

styled-components is actually an Open Source third party library, which lets you write actual CSS in your JavaScript. This means you can use all the features of CSS you use and love.

import styled from "styled-components";

const Button = styled.button`
    color: "red";
    border: "0";
`

const MyComp = () => {
    return <Button> Click Me! </Button>
}

I love SCSS modules in a CRA, but you can choose anyone depending on situation, there are other ways to style a component in CRA, but the above are the most popular ones.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!