How to use CSS in react App

In this article, I show you how we can use CSS in react application. There are several ways to use CSS in react app let’s discuss each one by one.

 

How to use CSS in react App

 

How to use CSS in React App

There below 3 ways that can be used to implement CSS in React App.

 

1. Inline Styles

The style prop is used to apply inline styles to a React component. This is a simple way to add styles to a single component, but it’s not recommended because it can quickly become difficult to manage if you have multiple components with similar styles.

Below is an example of an inline style prop in react –

function MyComponent() {
return <div style={{ backgroundColor: 'red', width: '100px' }}>Hello geekstutorials.com</div>;
}

 

2. CSS Style modules

CSS modules are a way to scope CSS to a specific component. This allows you to write CSS that is specific to a component and ensures that class names don’t conflict with other parts of the application.

import styles from './MyStyleComponent.module.css';

function MyComponent() {
return <div className={styles.container}>Hello geekstutorials.com</div>;;
}

Below is the CSS style component that is imported to MyComponent().

 

/* MyStyleComponent.module.css */
.container {
background-color: #ff0000;
width: 100px;
}

This is the most popular way to use CSS in react component. You can consider using this in your react app.

 

3. CSS-in-JS libraries

There are several libraries that allow you to write CSS in JavaScript. These libraries are often used in conjunction with a build process that generates CSS from JavaScript. Some popular libraries include styled-components, emotion, etc.

 

import styled from 'styled-components';

const MyStyledDiv = styled.div`
background-color: red;
width: 100px;
`;

function MyComponent() {
return <MyStyledDiv>Hello geekstutorials.com!</MyStyledDiv>;
}

 

The choice of how to use CSS in a React application depends on the specific requirements of the project and your personal preference.

 

Conclusion

This is how you can use the CSS in React application. The best practice is to keep your style separate from your react code.

I hope now you have the ability to implement the CSS in your react application.