0
0
ReactHow-ToBeginner · 3 min read

How to Use Inline Styles in React: Simple Guide

In React, use inline styles by passing a JavaScript object to the style attribute with camelCase property names. For example, <div style={{ backgroundColor: 'red' }}> sets a red background directly on the element.
📐

Syntax

Inline styles in React are written as a JavaScript object inside double curly braces. The outer braces indicate JavaScript expression, and the inner braces define the style object. CSS properties use camelCase instead of kebab-case.

  • style=: React attribute for inline styles
  • {{ ... }}: JavaScript object with style properties
  • camelCase: CSS properties like backgroundColor instead of background-color
  • values: Usually strings with units or color names
jsx
const style = { backgroundColor: 'blue', fontSize: '16px' };

function MyComponent() {
  return <div style={style}>Hello</div>;
}
Output
A div with blue background and 16px font size showing the text 'Hello'.
💻

Example

This example shows a React component with inline styles applied directly in the JSX. It changes the text color and adds padding.

jsx
import React from 'react';

export default function StyledBox() {
  return (
    <div style={{ color: 'white', backgroundColor: 'teal', padding: '20px', borderRadius: '8px' }}>
      This box has inline styles!
    </div>
  );
}
Output
A rectangular box with teal background, white text, 20px padding, and rounded corners displaying 'This box has inline styles!'.
⚠️

Common Pitfalls

Common mistakes when using inline styles in React include:

  • Using CSS property names with dashes instead of camelCase (e.g., background-color instead of backgroundColor).
  • Passing a string instead of an object to the style attribute.
  • Forgetting units like px for numeric values that require them.
  • Trying to use CSS pseudo-classes or media queries inside inline styles (which is not supported).
jsx
/* Wrong way: */
// <div style="background-color: red;">Wrong</div>  // style expects an object, not a string

/* Right way: */
// <div style={{ backgroundColor: 'red' }}>Correct</div>
📊

Quick Reference

ConceptExampleNotes
Style attribute
Use double curly braces for JS object
Property namesbackgroundColorCamelCase, not kebab-case
Values'16px', 'blue', 10Strings with units or numbers (numbers for unitless CSS)
Unsupported:hover, media queriesCannot use CSS selectors or media queries inline
Dynamic stylesstyle={{ fontSize: size + 'px' }}Can use JS expressions inside style object

Key Takeaways

Use a JavaScript object with camelCase properties inside double curly braces for inline styles.
Always pass an object to the style attribute, never a CSS string.
Include units like 'px' as strings for properties that require them.
Inline styles do not support CSS selectors or media queries.
You can use JavaScript expressions to set dynamic style values.