/

CSS in React: How to Style Your Application

CSS in React: How to Style Your Application

Using CSS to style a React application offers various options for developers. In this blog, we will explore three different methods: using classes and a CSS file, using the style attribute, and using CSS Modules.

Using Classes and CSS

The simplest way to style a React component is by using classes and a regular CSS file. To do this, define a class in your CSS file and target it in your component:

1
2
3
const Button = () => {
return <button className="button">A button</button>;
};
1
2
3
.button {
background-color: yellow;
}

To import the stylesheet, use an import statement in your component file:

1
import './style.css';

Webpack will automatically include the CSS file in the bundle.

Using the Style Attribute

Another method is to use the style attribute directly in your JSX element. This approach eliminates the need for a separate CSS file:

1
2
3
const Button = () => {
return <button style={{ backgroundColor: 'yellow' }}>A button</button>;
};

The CSS is defined as a JavaScript object inside double curly braces. Alternatively, you can define the style object outside the component:

1
2
3
4
5
const buttonStyle = { backgroundColor: 'yellow' };

const Button = () => {
return <button style={buttonStyle}>A button</button>;
};

When using create-react-app, styles are automatically prefixed using Autoprefixer. Also, note that the CSS properties are written in camelCase instead of using dashes.

Using CSS Modules

CSS Modules provide a middle ground between using classes and a separate CSS file. With CSS Modules, styles are scoped to the component, preventing them from affecting other parts of the application. Start by creating a CSS file with the .module.css extension, such as Button.module.css. Import the CSS file into your component:

1
import style from './Button.module.css';

You can then use the imported styles in your JSX:

1
2
3
const Button = () => {
return <button className={style.content}>A button</button>;
};

React will generate a unique class for each rendered component, ensuring that the styles are limited to the intended component.

Using these different methods, you can effectively style your React application. Each approach has its own advantages, so choose the one that best fits your project’s requirements.

CSS Modules in React

tags: [“React”, “CSS”, “styling”, “CSS Modules”]