Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

style prop value must be an object

React Error: style prop value must be an object

In this article, we will talk about style prop value must be an object. This is the error in react when we try to use style in the JSX element. Simply, when we try to pass style like in HTML, where we pass the attributes and values as a string.

style prop value must be an object

Problem

So let’s see how and when this problem occurs using an example:

<div className="container">
         <img src={myImageSource} alt="swimmer" height="300" width="300" style="float: left" />
         <p> This is where the other text goes about the swimmer</p>
 </div>

This is a little part of our JSX code, where we are trying to add some style to the image. Here we are trying to implement style="float: left" to apply this style to the image. As we know in HTML, we can use this same attribute to make it work, but in JSX this thing will cause errors.

Solution

There is a good solution to get rid of this error. So let’s see by modifying above code:

<div className="container">
         <img src={myImageSource} alt="swimmer" height="300" width="300" style= {{float: 'left'}} />
            <p> This is where the other text goes about the swimmer</p>
 </div>

As you can see, we have used double curly braces, and in this we have added the same properties. The idea behind using two curly braces is to tell react that whatever we’re passing in these two curly braces is our JS object, not a string.

Conclusion

We can see this problem, style prop value must be an object occurs when we try to apply the formal HTML code in which we mention style=”property: value”. Then this thing will be passed as a string to the JSX. This code will be worked in HTML, not in JSX. To get to run this code in the JSX, we need to pass this within double curly brackets {{property: value}}. This code will be considered as an object, and it will give corresponding effect.

Default image
reactjsguru
Articles: 44

Leave a Reply

Your email address will not be published.