Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

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 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.

style prop value must be an object

Table of Contents

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 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.

Conclusion

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.

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents

Table of Contents