Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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 the 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.
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.
There is a good solution to get rid of this error. So let’s see by modifying the 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.
We can see this problem, style prop value must be an object that 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 a corresponding effect.