How to fix CSS property not valid in React

ReactBEGINNERMEDIUMUpdated Dec 8, 2025ยท 177 views

React throws CSS property validation warnings when numeric style values are invalid, NaN, or missing required units. This occurs when inline style objects contain computed values that result in NaN or when non-px units are passed as numbers instead of strings.

Quick fix

Fixes CSS property not valid

function MyComponent({ containerWidth }) {
  // Bad: May result in NaN if containerWidth is invalid
  const width = parseFloat(containerWidth) / 2;

  // Good: Validate and provide fallback
  const width = !isNaN(parseFloat(containerWidth))
    ? parseFloat(containerWidth) / 2
    : 100; // Default fallback

  return <div style={{ width }}>{/* content */}</div>;
}
  1. Add validation checks before rendering computed style values
  2. Convert percentage and non-px units to strings
  3. Use unitless properties correctly
  4. Provide default values for optional props and state
react โ€” error
function MyComponent({ containerWidth }) {
// Bad: May result in NaN if containerWidth is invalid
const width = parseFloat(containerWidth) / 2;
// Good: Validate and provide fallback
const width = !isNaN(parseFloat(containerWidth))
? parseFloat(containerWidth) / 2
: 100; // Default fallback
return <div style={{ width }}>{/* content */}</div>;
}
CSS property not valid

What this error means

This error occurs when React detects invalid values in inline style objects. React has specific rules for handling numeric CSS properties: numbers are automatically converted to pixel values (e.g., `width: 10` becomes `"10px"`), but only for certain properties. When you pass invalid values like NaN, null, undefined, or pass numeric values for properties that require string units (like percentages or rem), React will warn that the CSS property value is invalid and strip the style from the rendered output. React maintains an internal list of properties that accept unitless numeric values (like `zIndex`, `fontWeight`, `opacity`, `flex`, and `order`). For all other properties, React expects either a number (which gets 'px' appended) or a string with an explicit unit. When your code produces invalid computed values or tries to use incompatible units, the browser cannot render the style properly, leading to layout issues and console warnings. This validation happens during the style object conversion phase before React passes the styles to the DOM. The error is React's way of preventing malformed CSS from reaching the browser, which would silently fail and cause hard-to-debug layout problems.

Typical symptoms

  • Console warning: "NaN is an invalid value for the [property] css style property"
  • Inline styles not being applied to elements despite correct JSX syntax
  • Component renders but layout appears broken or unstyled
  • Styles work with hardcoded values but fail when using computed values
  • Width, height, margin, or padding properties not rendering as expected
  • React development tools show style object with invalid or missing values
  • Style properties are silently stripped from the rendered DOM element

Common causes

  1. Passing NaN as a style value due to failed mathematical operations (e.g., dividing by zero, parsing invalid strings)
  2. Using numeric values for properties that require string units like percentages ("50%"), viewport units ("10vh"), or relative units ("2em")
  3. Computed style values that return undefined or null instead of valid numbers
  4. Attempting to use string values with semicolons or CSS syntax in inline style objects
  5. Passing numeric strings (e.g., "10") instead of numbers for px-based properties in React 16+
  6. Using properties that expect unitless values but providing units (e.g., opacity: "0.5px" instead of opacity: 0.5)
  7. Referencing state or prop values that haven't been initialized or are undefined during initial render
  8. Type mismatches in TypeScript where number types are expected but strings are provided

How to fix "CSS property not valid"

1Add validation checks before rendering computed style values

Before using computed values in inline styles, validate that they are valid numbers:

jsx
function MyComponent({ containerWidth }) {
  // Bad: May result in NaN if containerWidth is invalid
  const width = parseFloat(containerWidth) / 2;

  // Good: Validate and provide fallback
  const width = !isNaN(parseFloat(containerWidth))
    ? parseFloat(containerWidth) / 2
    : 100; // Default fallback

  return <div style={{ width }}>{/* content */}</div>;
}

Use Number.isNaN() or isFinite() to check values before applying them to styles. This prevents NaN or Infinity from reaching the style object.

2Convert percentage and non-px units to strings

When using units other than pixels, always pass the value as a string with the unit specified:

jsx
// Bad: React cannot convert numbers to non-px units
<div style={{ width: 50, height: 100 }}>  {/* Results in width: 50px, height: 100px */}

// Bad: Trying to use percentage as number
<div style={{ width: 50% }}>  {/* Syntax error */}

// Good: Use strings for non-px units
<div style={{
  width: '50%',
  height: '100vh',
  padding: '2em',
  margin: '1rem'
}}>

// Good: Construct strings dynamically for computed percentages
const widthPercent = `${(containerWidth / totalWidth) * 100}%`;
<div style={{ width: widthPercent }}>

Remember: numbers = pixels, strings = any unit.

3Use unitless properties correctly

For properties that accept unitless values, use numbers without strings:

jsx
// Unitless properties that accept plain numbers:
<div style={{
  opacity: 0.5,        // Not "0.5" or "0.5px"
  zIndex: 100,         // Not "100"
  flex: 1,             // Not "1"
  flexGrow: 2,         // Not "2"
  flexShrink: 1,       // Not "1"
  fontWeight: 700,     // Not "700"
  lineHeight: 1.5,     // Not "1.5"
  order: 3             // Not "3"
}}>

// Wrong: Adding units to unitless properties
<div style={{
  opacity: '0.5px',    // Invalid
  zIndex: '100px',     // Invalid
  flex: '1px'          // Invalid
}}>

Check the [React DOM Elements documentation](https://legacy.reactjs.org/docs/dom-elements.html) for the full list of unitless properties.

4Provide default values for optional props and state

Initialize state and provide default props to prevent undefined values in style calculations:

jsx
// Bad: May be undefined on first render
function Component({ width }) {
  return <div style={{ width }}>{/* content */}</div>;
}

// Good: Provide default props
function Component({ width = 200 }) {
  return <div style={{ width }}>{/* content */}</div>;
}

// Good: Use nullish coalescing for state
function Component() {
  const [height, setHeight] = useState(null);

  return (
    <div style={{
      height: height ?? 100  // Use 100 if height is null/undefined
    }}>
      {/* content */}
    </div>
  );
}

This ensures styles always have valid values, even before async data loads or user interactions occur.

5Remove CSS syntax from inline style objects

React inline styles use JavaScript objects, not CSS strings. Remove semicolons, quotes around property names, and CSS-specific syntax:

jsx
// Wrong: CSS syntax in object
<div style={{
  "width": "100px";
  "height": "50px";
}}>

// Wrong: Semicolons in values
<div style={{
  width: '100px;',
  height: '50px;'
}}>

// Correct: JavaScript object syntax
<div style={{
  width: '100px',
  height: '50px'
}}>

// Correct: CamelCase property names
<div style={{
  backgroundColor: '#fff',  // Not background-color
  fontSize: '16px',         // Not font-size
  borderRadius: '4px'       // Not border-radius
}}>

Style objects use camelCase property names and commas (not semicolons) between properties.

6Debug by logging style values before rendering

Add console logging to inspect computed style values and identify which property is invalid:

jsx
function Component({ data }) {
  const computedWidth = calculateWidth(data);
  const computedHeight = data.height / data.scale;

  // Debug: Log values to see what's being computed
  console.log('Style values:', {
    width: computedWidth,
    height: computedHeight,
    isWidthValid: !isNaN(computedWidth),
    isHeightValid: !isNaN(computedHeight)
  });

  const style = {
    width: computedWidth,
    height: computedHeight
  };

  return <div style={style}>{/* content */}</div>;
}

Use React DevTools to inspect the actual style object in the component tree. If a property shows as NaN, null, or undefined, trace back through your calculation logic.

7Use TypeScript for type safety with CSS properties

Enable TypeScript to catch type mismatches in style objects at compile time:

typescript
import { CSSProperties } from 'react';

interface ComponentProps {
  width?: number | string;
}

function Component({ width = 200 }: ComponentProps) {
  // TypeScript ensures style object matches CSSProperties interface
  const style: CSSProperties = {
    width: typeof width === 'number' ? width : width,
    // TypeScript will error if you try: opacity: '0.5px'
    opacity: 0.5,
    // TypeScript will error if you try: zIndex: '100'
    zIndex: 100
  };

  return <div style={style}>{/* content */}</div>;
}

TypeScript's CSSProperties type provides autocomplete and validation for all valid CSS properties and their expected value types.

Advanced notes

React 16+ Behavior Change: In React 15, numeric strings like "10" were accepted (with a warning) and converted to "10px". React 16+ passes numeric strings as-is without conversion, which may cause styles to break if you're upgrading from older versions. Always use actual numbers (not numeric strings) for pixel values.

Performance Consideration: While inline styles are convenient, they create new style objects on every render. For static styles, consider using CSS classes or CSS-in-JS libraries like styled-components or emotion, which provide better caching and type safety.

Custom CSS Properties (CSS Variables): When using CSS custom properties in inline styles, always pass them as strings: style={{ '--custom-width': '100px' }}. Numbers won't work for CSS variables.

Server-Side Rendering: Style validation errors may appear differently or at different times when using SSR. Ensure style calculations don't depend on browser-only APIs (like window.innerWidth) during server rendering, or conditionally apply them after hydration.

Browser DevTools: Some browsers silently ignore invalid CSS values without warnings. React's validation helps catch these issues during development that might otherwise go unnoticed until layout breaks in production.

Frequently asked questions

What does "CSS property not valid" mean?
This error occurs when React detects invalid values in inline style objects. , width: 10 becomes "10px"), but only for certain properties. When you pass invalid values like NaN, null, undefined, or pass numeric values for properties that require string units (like percentages or rem), React will warn that the CSS property value is invalid and strip the style from the rendered output.
How do I fix "CSS property not valid"?
React throws CSS property validation warnings when numeric style values are invalid, NaN, or missing required units. This occurs when inline style objects contain computed values that result in NaN or when non-px units are passed as numbers instead of strings.
What causes "CSS property not valid"?
Passing NaN as a style value due to failed mathematical operations (e.g., dividing by zero, parsing invalid strings) Using numeric values for properties that require string units like percentages ("50%"), viewport units ("10vh"), or relative units ("2em") Computed style values that return undefined or null instead of valid numbers
Is the "CSS property not valid" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading