(React) The `style` prop expects a mapping from style properties to values

avatar

Borislav Hadzhiev

Last updated: Apr 18, 2022

banner

Check out my new book

(React) The style prop expects a mapping from style properties to values #

The error "The style prop expects a mapping from style properties to values, not a string" occurs when we pass a string to the style prop of an element in React. To solve the error, use a mapping from properties to values, e.g. style={{marginLeft: '2rem'}}.

the style prop expects a mapping from style properties

Here is an example of how the error occurs.

App.js
const App = () => { // ⛔️ Uncaught Error: The `style` prop expects a mapping from style properties to values, not a string. // For example, style={{marginRight: spacing + 'em'}} when using JSX. return ( <div> <h2 style="background-color: lime;">Hello world</h2> </div> ); }; export default App;

The issue is that we're passing a string to the style prop of the h2 element. Instead, the style prop should be a mapping from properties to values.

App.js
const App = () => { return ( <div> <h2 style={{ backgroundColor: 'lime', marginLeft: '10px', padding: '2rem', fontSize: '2rem', }} > Hello world </h2> </div> ); }; export default App;

Notice that we used 2 sets of curly braces. The outer set of curly braces evaluates an expression, and the inner set is the object containing property names and values.

You can also use logic to calculate a specific value.

App.js
const App = () => { return ( <div> <h2 style={{ backgroundColor: 'lime', marginLeft: 5 + 5 + 'px', padding: 1 + 1 + 'rem', fontSize: '2rem', }} > Hello world </h2> </div> ); }; export default App;

You can also extract the object of properties and values into a variable.

App.js
const App = () => { const h2Styles = { backgroundColor: 'lime', marginLeft: 5 + 5 + 'px', padding: 1 + 1 + 'rem', fontSize: '2rem', }; return ( <div> <h2 style={h2Styles}>Hello world</h2> </div> ); }; export default App;

Notice that names of CSS properties must be camelCased. An alternative is to write your CSS in a file with a .css extension and use the className prop to style your elements.

Here is how we would move the styles for the h2 element into a class in a file called App.css.

App.css
.my-h2 { background-color: lime; margin-left: 10px; padding: 2rem; font-size: 2rem; }

Now we can import the css file and use the my-h2 class.

App.js
import './App.css'; const App = () => { return ( <div> <h2 className="my-h2">Hello world</h2> </div> ); }; export default App;

This is an alternative to inlining styles. Notice that the prop is called className and not class. The reason being - class is a reserved word in JavaScript. The class keyword is used to declare ES6 classes.

Use the search field on my Home Page to filter through my more than 3,000 articles.