React CSS Styling

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

Tutorials dojo strip
  • 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:

JavaScript

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:

JavaScript

JavaScript Object

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

Create a style object named styleObject:

JavaScript

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:

JavaScript

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

Import the Stylesheet in Your Application:

JavaScript

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:

JavaScript

Import the Stylesheet in Your Component:

JavaScript

Import the Component in Your Application:

JavaScript
Tutorials dojo strip