Borislav Hadzhiev
Mon Apr 18 2022·2 min read
Photo by Nadia Jamnik
The warning "Style prop value must be an object" occurs when we pass a string
to the style
prop of an element in React. To fix the warning, use a mapping
from properties to values, e.g. style={{paddingLeft: '15px'}}
.
Here is an example of how the warning is caused.
const App = () => { // ⛔️ Style prop value must be an object eslint(react/style-prop-object) return ( <div> <h1 style="margin-left: 4rem">Hello world</h1> </div> ); }; export default App;
The issue is that we're passing a string
to the style
prop of the h1
element. Instead, the style
prop should be a mapping from properties to
values.
const App = () => { return ( <div> <h1 style={{ marginLeft: '4rem', fontSize: '20px', padding: '20px', backgroundColor: 'salmon', color: 'white', }} > Hello world </h1> </div> ); }; export default App;
You can also use logic to calculate a specific value.
const App = () => { return ( <div> <h1 style={{ marginLeft: 2 + 2 + 'rem', fontSize: Math.random() > 0.5 ? '20px' : '40px', padding: '20px', backgroundColor: 'salmon', color: 'white', }} > Hello world </h1> </div> ); }; export default App;
You can also extract the object of properties and values into a variable.
const App = () => { const h1Styles = { marginLeft: 2 + 2 + 'rem', fontSize: Math.random() > 0.5 ? '20px' : '40px', padding: '20px', backgroundColor: 'salmon', color: 'white', }; return ( <div> <h1 style={h1Styles}>Hello world</h1> </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 h1
element into a class in a file
called App.css
.
.my-h1 { margin-left: 4rem; font-size: 20px; padding: 20px; background-color: salmon; color: white; }
Now we can import the css
file and use the my-h1
class.
import './App.css'; const App = () => { return ( <div> <h1 className="my-h1">Hello world</h1> </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.