How to Add Style in JSX: Simple React Styling Guide
In JSX, you add styles by using the
style attribute with a JavaScript object for inline styles or by applying CSS classes with the className attribute. Inline styles use camelCase property names and values as strings or numbers, while className connects to CSS rules defined elsewhere.Syntax
To add inline styles in JSX, use the style attribute with a JavaScript object where CSS properties are camelCased and values are strings or numbers. For CSS classes, use the className attribute instead of class.
- style: An object with CSS properties in camelCase.
- className: A string with CSS class names.
jsx
/* Inline style syntax */ <div style={{ backgroundColor: 'blue', fontSize: '16px' }}>Text</div> /* CSS class syntax */ <div className="my-class">Text</div>
Example
This example shows a React component with inline styles and CSS classes applied to elements. It demonstrates how styles affect the rendered output.
jsx
import React from 'react'; const StyledComponent = () => { const inlineStyle = { color: 'white', backgroundColor: 'teal', padding: '10px', borderRadius: '5px' }; return ( <div> <h2 style={inlineStyle}>This is styled with inline styles</h2> <p className="text-highlight">This is styled with a CSS class</p> </div> ); }; export default StyledComponent;
Output
A heading with white text on teal background and rounded corners, and a paragraph styled by CSS class.
Common Pitfalls
Common mistakes include:
- Using
classinstead ofclassNamein JSX. - Writing CSS properties in kebab-case (like
background-color) instead of camelCase (backgroundColor) in inline styles. - Passing style values without quotes or as numbers when strings are required (e.g.,
fontSize: 16is valid, butfontSize: 16pxis not).
jsx
/* Wrong: Using class instead of className */ // <div class="my-class">Text</div> /* Right: Use className */ // <div className="my-class">Text</div> /* Wrong: CSS property in kebab-case */ // <div style={{ 'background-color': 'red' }}>Text</div> /* Right: Use camelCase */ // <div style={{ backgroundColor: 'red' }}>Text</div>
Quick Reference
| Attribute | Usage | Notes |
|---|---|---|
| style | style={{ camelCaseProperty: 'value' }} | Inline styles as JS object, camelCase keys |
| className | className="css-class" | Use for CSS classes, not 'class' |
| CSS property names | backgroundColor, fontSize | Use camelCase, not kebab-case |
| Style values | '16px', 16 | Strings with units or numbers for unitless properties |
Key Takeaways
Use the style attribute with a camelCase JavaScript object for inline styles in JSX.
Always use className instead of class to apply CSS classes in JSX.
CSS property names in inline styles must be camelCase, not kebab-case.
Style values should be strings with units or numbers for unitless properties.
Avoid common mistakes like using class or wrong property names to ensure styles apply correctly.