Curriculum
Course: React
Login

Curriculum

React

Text lesson

React CSS Styling

There are several methods to style React components with CSS. This tutorial will focus on three common approaches:

  • Inline styling
  • CSS stylesheets
  • CSS Modules

Inline Styling

To apply inline styles to an element, the value of the style attribute must be a JavaScript object.

Example:

Insert a JavaScript object containing the styling details.

const Header = () => {
 return (
    <>
      <h1 style={{color: "red"}}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
 );
}
Note: In JSX, JavaScript expressions are enclosed in curly braces, and since objects also use curly braces, the styling in the example above is written within double curly braces {{}}.

 

camelCased Property Names

Since inline CSS is written as a JavaScript object, properties with hyphens, such as background-color, must be written in camelCase as backgroundColor.

Example:

Use backgroundColor instead of background-color.

const Header = () => {
 return (
    <>
      <h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
 );
}

JavaScript Object

You can also create a separate object with the styling information and reference it in the style attribute.

Example:

Create a style object called myStyle.

const Header = () => {
 const myStyle = {
    color: "white",
    backgroundColor: "DodgerBlue",
    padding: "10px",
    fontFamily: "Sans-Serif"
 };
 return (
    <>
      <h1 style={myStyle}>Hello Style!</h1>
      <p>Add a little style!</p>
    </>
 );
}