A badge, styled inline
This sale badge gets its whole look from the style prop:
export default function SaleBadge() { return ( <span style={{ backgroundColor: '#2f855a', color: 'white', padding: '4px 10px', borderRadius: 999 }}> 2 for 1 on lattes </span> );}
Open in React Playground
On the right is what React wrote into the page. Each key in the object became a normal CSS property:
backgroundColor turned into background-color, and borderRadius: 999 into
border-radius:999px. React doesn’t do anything clever with the result. It’s an ordinary
style attribute, the same as one you’d write by hand in HTML.
style takes an object
The double braces in style={{ … }} look odd at first. The outer pair means “a JavaScript value
starts here”, and the inner pair is the object. Because it’s an ordinary object, you can also keep it in a
variable and reuse it:
const cardStyle = { maxWidth: 260, padding: 16, border: '1px solid #d1d5db', borderRadius: 12,};export default function MenuCard() { return ( <div style={cardStyle}> <h3 style={{ margin: 0 }}>Flat white</h3> <p style={{ margin: '4px 0 0', color: '#4b5563' }}>Double shot, silky milk. $3.90</p> </div> );}
Open in React Playground
style={cardStyle} has single braces this time, because cardStyle is already an
object. Copy an HTML style string straight into JSX, though, and React stops with an error:
function Price() { return <p style="color: green">$3.90</p>;}
The message is “The style prop expects a mapping from style properties to values, not a string.” The
HTML to JSX converter rewrites style strings into objects if you have a lot of them to
move over.
camelCase property names
CSS names with dashes become camelCase: drop each dash and capitalize the letter after it. Values that aren’t plain numbers are strings, so they go in quotes.
| CSS | In a style object |
|---|---|
background-color: #fef3c7 | backgroundColor: '#fef3c7' |
font-size: 18px | fontSize: 18 |
border-top-left-radius: 8px | borderTopLeftRadius: 8 |
z-index: 10 | zIndex: 10 |
font-family: Georgia, serif | fontFamily: 'Georgia, serif' |
-webkit-line-clamp: 2 | WebkitLineClamp: 2 |
If you write the dashed name anyway, as { 'background-color': 'red' }, React still outputs it but
warns in the console: “Unsupported style property background-color. Did you mean backgroundColor?” Commas between
properties, not semicolons: it’s a JavaScript object, so { color: 'white', padding: 8 }.
Numbers, px and unitless values
A plain number means pixels for anything that’s a size. For properties that don’t take units, React leaves the number alone. Anything else goes in a string with its unit:
export default function Sizes() { return ( <div> <p style={{ fontSize: 20, marginBottom: 8 }}>fontSize: 20 is 20px</p> <p style={{ lineHeight: 2, opacity: 0.6 }}>lineHeight: 2 and opacity: 0.6 stay as they are</p> <p style={{ width: '60%', padding: '4px 8px', background: '#fef3c7' }}>Other units go in quotes</p> </div> );}
Open in React Playground
React keeps a list of the properties that shouldn’t get px. The ones you’ll use most are
lineHeight, opacity, zIndex, fontWeight,
flexGrow, flexShrink, order and aspectRatio. That has one
trap: lineHeight: 24 doesn’t mean 24px, it means 24 times the font size. Write
lineHeight: '24px' or, better, something like lineHeight: 1.5.
For %, rem, em, vh and values with more than one part
('4px 8px', '1px solid #d1d5db'), use a string. A number in a string gets no unit at
all, so width: '200' becomes width:200, which the browser ignores. And a value of
null, undefined, false or '' leaves the property out, which is
how you add styles you only want sometimes.
Vendor prefixes
React doesn’t add prefixes like -webkit- for you. When you need one, write it yourself: the
prefix starts with a capital letter, and the rest is camelCase. This review stops after two lines:
const twoLines = { display: '-webkit-box', WebkitBoxOrient: 'vertical', WebkitLineClamp: 2, overflow: 'hidden',};export default function Review() { return ( <p style={{ ...twoLines, maxWidth: 280 }}> Best flat white in town. The milk is silky, the beans are roasted down the road, and they remember your name after two visits. Get there before 9 or be ready to queue. </p> );}
Open in React Playground
WebkitLineClamp became -webkit-line-clamp. The odd one out is Microsoft’s old prefix,
which starts with a small letter: msTransform. Today you’ll rarely need any of them apart from a few
like this line clamp. Since an object can only have each key once, you also can’t write a fallback such as
display: -webkit-box followed by display: flex inline. That kind of thing belongs in a CSS
file.
Styles that change with state
Inline styles are most useful for values that change. The value can come from state, props or a calculation, and React updates the element when it changes. Run this one in the playground and drag the slider:
import { useState } from 'react';export default function StrengthPicker() { const [strength, setStrength] = useState(3); const percent = (strength / 5) * 100; return ( <div style={{ maxWidth: 300 }}> <label> Coffee strength: {strength} of 5 <input type="range" min="1" max="5" value={strength} onChange={(e) => setStrength(Number(e.target.value))} style={{ display: 'block', width: '100%' }} /> </label> <div style={{ height: 12, borderRadius: 6, background: '#e5e7eb' }}> <div style={{ width: `${percent}%`, height: '100%', borderRadius: 6, background: strength >= 4 ? '#7c2d12' : '#d97706', transition: 'width 0.2s', }} /> </div> </div> );}
Open in React Playground
The bar’s width is worked out from the strength, `${percent}%` adds the unit, and the color goes
darker from 4 up. transition smooths the change. A progress bar, the position of something being
dragged, or a color the person picked: values like these are different for every person and every moment, so a
fixed class can’t hold them.
CSS variables (custom properties)
Keys that start with two dashes are passed through as they are. That lets you set a CSS variable inline and use it
from a stylesheet. The value comes from React, and the CSS file can still use it in a :hover rule:
function BrandButton({ accent, children }) { return ( <button className="brand-button" style={{ '--accent': accent }}> {children} </button> );}export default function App() { return ( <div> <BrandButton accent="#2f855a">Order a matcha</BrandButton> <BrandButton accent="#be185d">Order a berry tea</BrandButton> </div> );}
Open in React Playground
Hover the buttons in the live box: each one gets darker in its own color, because the :hover rule
uses var(--accent). Custom properties never get px added, so pass
'16px' rather than 16 if the CSS uses it as a size. In TypeScript, the style object’s type
doesn’t know your variable names, so { '--accent': accent } is an error until you cast it:
import type { CSSProperties, ReactNode } from 'react';type BrandButtonProps = { accent: string; children: ReactNode };function BrandButton({ accent, children }: BrandButtonProps) { const style = { '--accent': accent } as CSSProperties; return ( <button className="brand-button" style={style}> {children} </button> );}export default function App() { return <BrandButton accent="#2f855a">Order a matcha</BrandButton>;}
Open in React Playground
No :hover or media queries inline
A style attribute applies to one element, always. It has no way to say “only when hovered”, “only on small
screens” or “the ::before part”. Those need a selector, and selectors live in a stylesheet. So give the
element a class:
import './MenuButton.css';export default function MenuButton() { return <button className="menu-button">See the menu</button>;}
Open in React Playground
.menu-button { padding: 10px 18px; border: 0; border-radius: 8px; background: #2f855a; color: white; font: inherit; cursor: pointer;}.menu-button:hover,.menu-button:focus-visible { background: #22543d;}@media (max-width: 480px) { .menu-button { width: 100%; }} import './MenuButton.css' is how Vite and Next.js projects load a stylesheet for a component. The
playground can’t load files, so its link puts the same rules in the CSS tab. You can fake hover with
onMouseEnter, onMouseLeave and a bit of state, but it’s more code, it redraws the
component on every hover, and people using a keyboard never see it. :hover and
:focus-visible in CSS cover both.
className and a CSS file
For most styling, classes are the better default. The rules are written once and shared by every element with the
class, and the CSS file can use everything CSS has. Inline styles and classes also mix well: let the class do the
look, and let style handle the one value that comes from data:
import './Card.css';export default function Card({ highlight }) { return ( <div className="card" style={{ borderColor: highlight }}> Today: pumpkin spice latte </div> );}
One thing to know when you mix them: an inline style beats any rule in a stylesheet, so a class can’t override
borderColor here unless its rule uses !important. In bigger projects you’ll also see CSS
Modules (import styles from './Card.module.css', then className={styles.card}),
which keep class names from clashing, and utility classes such as Tailwind, which put the styling into
className itself.
When inline styles are fine
Plenty of good React code uses style. It’s a good fit for:
- Values that come from state, props or a calculation: widths, positions, a color someone picked.
- Setting a CSS variable for a stylesheet to use, like the brand buttons above.
- A one-off tweak, such as
style={{ marginTop: 0 }}on one heading. - Quick prototypes and examples, where a separate CSS file would only slow you down.
Reach for a class instead when you need :hover, :focus, media queries, animations with
@keyframes or ::before, or when the same styles repeat on many elements. A list of 200 menu
items with the same eight inline properties writes those properties 200 times into the page; one class writes them
once.
Common mistakes
- A style string.
style="color: green"throws. Usestyle={{ color: 'green' }}. - Single braces.
style={color: 'green'}is a syntax error. You need the outer braces for “JavaScript here” and the inner ones for the object. - A size in a string without its unit.
fontSize: '18'givesfont-size:18, which the browser ignores. UsefontSize: 18orfontSize: '18px'. - lineHeight as pixels.
lineHeight: 24is 24 times the font size, not 24px. - !important. The browser rejects the value when React sets it, so it doesn’t stick:
// Doesn't stick: React's update in the browser drops "!important"<p style={{ color: 'red !important' }}>Sold out</p> - Fix: if you need to beat another rule that badly, move both into CSS and sort out the selectors there, or use a more specific class.
- Dashed names.
{ 'font-size': 18 }still works, but React warns about it in the console. UsefontSize.
Questions people ask
How do I write inline styles in React?
Pass an object to the style prop: style={{ color: "white", backgroundColor: "#2f855a", padding: 8 }}. Property names are camelCase, text values go in quotes, and properties are separated by commas. React turns it into a normal style attribute, here style="color:white;background-color:#2f855a;padding:8px".
Why does React use double curly braces for style?
The outer braces mean “a JavaScript value starts here”, the same as {name} anywhere in JSX. The inner braces are the object itself. If the object is in a variable, you only need one pair: style={cardStyle}.
Does React add px to numbers in styles?
Yes, for properties that are sizes: fontSize: 18 becomes font-size:18px and padding: 8 becomes padding:8px. Properties without units keep the plain number, such as lineHeight, opacity, zIndex, fontWeight, flexGrow and order. For other units (%, rem, vh) or several values, use a string like "50%" or "4px 8px".
Can I use :hover or media queries in React inline styles?
No. A style attribute applies to the element all the time, so it can’t express :hover, :focus, media queries or ::before. Give the element a className and write those rules in a CSS file. You can set a CSS variable inline, like style={{ "--accent": color }}, and use var(--accent) inside the :hover rule.
How do I set a CSS variable in a React style prop?
Use the variable name as a quoted key: style={{ "--accent": "#2f855a" }}. React passes it through unchanged and never adds px, so include units yourself. In TypeScript the style type doesn’t know custom properties, so cast it: { "--accent": accent } as CSSProperties.
Why do I get “The style prop expects a mapping from style properties to values, not a string”?
Because the style is written as an HTML string, like style="color: red". In React it has to be an object: style={{ color: "red" }}. The HTML to JSX converter can rewrite style strings into objects for you.
Should I use inline styles or CSS classes in React?
Use classes (a CSS file, CSS Modules or utility classes) for most styling, especially anything with hover, focus, media queries or styles shared by many elements. Use inline styles for values that change with state or props, like a progress bar width, a position or a color someone picked, and for setting CSS variables.
How do I add vendor prefixes in React inline styles?
React doesn’t add them for you, so write them yourself in camelCase with a capital first letter: WebkitLineClamp: 2 becomes -webkit-line-clamp:2. The old Microsoft prefix is the exception and starts lowercase: msTransform.