Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline style is not working ReactJS

Tags:

reactjs

I am trying to learn React. Why can you not use style inside of a return inside of a component?

The Error:

The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by Home.

<div className="single_slide" style="background-image: url(../images/WinterCalling_2016.jpg);">

I have also tried this also:

<div className="single_slide" style={{background-image: 'url(../images/WinterCalling_2016.jpg)'}}>

or

<div className="single_slide" style={{background-image: url(../images/WinterCalling_2016.jpg)}}>

Any help with this syntax would be greatly appreciated. Other people posted they change style to say styles but that did not seem to work either.

like image 324
David Brierton Avatar asked May 22 '17 02:05

David Brierton


1 Answers

From DOC:

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string.

So instead of background-image use backgroundImage.

For example:

padding-top      --->     paddingTop

padding-left     --->     paddingLeft

margin-right     --->     marginRight

...

How to specify the inline style?

We need to pass a object to style attribute which will contains all the values in form of key-value pair.

Like this:

<div 
    style={{
       backgroundImage: 'url(../images/WinterCalling_2016.jpg)', 
       marginTop: 20}}
>

Update:

We can use template literals to pass a variable inside url, like this:

<div style={{backgroundImage: `url(${image1})`}}>
like image 52
Mayank Shukla Avatar answered Oct 09 '22 12:10

Mayank Shukla