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.
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.
Before using computed values in inline styles, validate that they are valid numbers:
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.
When using units other than pixels, always pass the value as a string with the unit specified:
// 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.
For properties that accept unitless values, use numbers without strings:
// 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.
Initialize state and provide default props to prevent undefined values in style calculations:
// 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.
React inline styles use JavaScript objects, not CSS strings. Remove semicolons, quotes around property names, and CSS-specific syntax:
// 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.
Add console logging to inspect computed style values and identify which property is invalid:
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.
Enable TypeScript to catch type mismatches in style objects at compile time:
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.
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.
React Hook useCallback has a missing dependency: 'variable'. Either include it or remove the dependency array react-hooks/exhaustive-deps
React Hook useCallback has a missing dependency
Cannot use private fields in class components without TS support
Cannot use private fields in class components without TS support
Cannot destructure property 'xxx' of 'undefined'
Cannot destructure property of undefined when accessing props
useNavigate() may be used only in the context of a <Router> component.
useNavigate() may be used only in the context of a Router component
Cannot find module or its corresponding type declarations
How to fix "Cannot find module or type declarations" in Vite