React CSS Styling

There are several methods to style React components with CSS. Here are three methods you can use.

  • Inline Styling
  • CSS Stylesheets
  • CSS Modules



Inline Styling

To apply styles directly to an element using the style attribute, the value should be a JavaScript object:

Embed an object containing the styling details:

JS

Note: In JSX, JavaScript expressions are enclosed in curly braces, and since JavaScript objects also use curly braces, the styling above uses double curly braces {{}}.




camelCased Property Names

When using inline CSS in a JavaScript object, properties with hyphen separators like background-color should be written in camelCase:

Use backgroundColor instead of background-color:

JS




JavaScript Object

You can also define an object containing styling details and reference it in the style attribute:

Create a style object named styleObject:

JS




CSS Stylesheet

CSS styles can be written in a separate file. Save the file with a .css extension and import it into your application.

App.css:

Create a new file named App.css and add some CSS code:

CSS

Note: You can name the file as you prefer, just ensure it has the correct file extension.


Import the Stylesheet in Your Application:

JS




CSS Modules

Another way to add styles to your application is using CSS Modules. CSS Modules are convenient for components that are placed in separate files. The CSS in a module is scoped to that component, avoiding conflicts.

Create the CSS module with the .module.css extension, for example: custom-style.module.css.

custom-style.module.css:

CSS

Import the Stylesheet in Your Component:

JS

Import the Component in Your Application:

JS