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 byHome
.
<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.
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})`}}>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With