Codecademy Logo

React Styles

Related learning

React CSS Styles

React supports inline CSS styles for elements. Styles are supplied as a style prop with a JavaScript object.

// Passing the styles as an object
const color = {
color: 'blue',
background: 'sky'
};
<h1 style={color}>Hello</h1>
// Passing the styles with an inline object, as a shorthand
<h1 style={{ color: 'red' }}>I am red!</h1>

Style Names And Values

In React, style names are written in “camelCase”, unlike in CSS where they are hyphenated. In most cases, style values are written as strings. When entering numeric values, you don’t have to enter px because React automatically interprets them as pixel values.

// Styles in CSS:
// font-size: 20px;
// color: blue;
// Would look like this style object in React:
const style = {
fontSize: 20,
color: 'blue',
};

React CSS Modules

CSS Modules provide a way to scope styles locally to individual React components by automatically transforming class names into unique identifiers at build time. This prevents unintended style conflicts across the application and eliminates the need for complex naming conventions.

By separating styles into dedicated module files, components maintain better organization and modularity. Each component’s styles remain isolated, making it easier to locate and maintain styling logic without worrying about class name collisions.

/* Button.module.css */
.button {
padding: 10px 20px;
background-color: blue;
color: white;
}
/* Button.js */
import styles from './Button.module.css';
function Button({ children }) {
return (
<button className={styles.button}>
{children}
</button>
);
}

Learn more on Codecademy