React
  • Introduction
  • Getting Started
    • Introduction
    • Before you get started
  • 1. Fundamentals
    • Introduction
    • Rendering
      • JSX
      • Exercise
      • Solution
    • Components
      • Stateless
        • Exercise
        • Solution
      • Stateful
        • Exercise
        • Solution
      • Styling
        • Exercise
        • Solution
        • Using CSS Modules
    • Folder Architecture
  • 2. Intermediate
    • Lifecycle methods
    • Controlled and Uncontrolled components
    • Anti-patterns
    • Refs and the DOM
    • Lifting State Up
  • 3. Advanced Topics
    • Conventions
    • Reconciliation
    • Performance Optimizations
      • Avoiding Reconciliation
      • PureComponent
      • Avoiding inline lambdas
      • Development vs Production build
    • Context
  • 4. Advanced Patterns
    • Higher-order Components
    • Children as Function
    • Renderless Components
    • Portals
    • Error handling
  • Exercises
    • Introduction
    • 1. ProductList light
      • Step 1
      • Step 2
      • Step 3
      • Step 4
      • Extra
      • Solution
Powered by GitBook
On this page
  • Inline styles
  • CSS classes
  • Further reading
  1. 1. Fundamentals
  2. Components

Styling

React components are styled very similarly to how you would natively style an HTML element. You have two options: CSS classes and inline styles. These styles are passed into a component by using props.

Inline styles

To add inline styles to your HTML elements, you just have to use the style property and pass it a JavaScript object defining your styles. You will notice that the keys of the CSS properties are camelCase, so font-size becomes fontSize.

Here is an example:

<input style={{
  width: 150,
  border: '1px solid #000',
  fontSize: 18, // camelCase for CSS properties that contain hyphens
}} />

CSS classes

The other basic way of styling your elements is to pass it the class attribute. As class is a reserved keyword in JavaScript, we will use the props className.

Example:

<input className="form-control"/>

Note: Since JSX is closer to JavaScript than HTML, React uses the camelCase property naming convention. You’ll notice that other properties such as tabindex become tabIndex.

create-react-app have webpack configured to be able to import a CSS file into your components. That gives you a way to have a .css file next to your component and import it.

To use it, you just have to define your CSS and import it in your component:

.Component {
  max-width: 540px;
  margin: 0 auto;
  padding: 40px 20px;
}
  import './Component.css';

Further reading

There are a number of other ways to style React Components, here are a few:

CSS-in-JS:

Inline Styles:

PreviousSolutionNextExercise

Last updated 6 years ago

For a more exhaustive list comparing these different options, check out

CSS Modules
Styled Components
Glamorous
styled-jsx
Aphrodite
Radium
https://github.com/MicheleBertoli/css-in-js