My question involves styling react components inline.
I understand that within JSX {variableName}
, braces are needed to reference any JS variable or expression.
So, adding an inline style using the following construct makes sense to me. The desired style is stored in a JavaScript variable, then referenced within the JSX "tag" as style={divStyle}
const divStyle = {
backgroundImage: `url(${avatarURL})`,
};
function HelloWorldComponent() {
return (
<div className='avatar' style={divStyle}>
Hello World!
</div>;
)
}
But I do not see the connection with the syntax of style={{..}}
when the style is typed directly into the JSX "tag" as in the following:
function HelloWorldComponent() {
return (
<div className='avatar' style={{backgroundImage: `url(${avatarURL})`}}>
Hello World!
</div>;
)
}
Can someone explain the logic behind the style={{..}}
construct ?
I see this in docs and other reference materials, but I haven't seen any explanation, it's just passed over as though obvious.
As this was not an obvious extension of the JS expression rule to me, I was using only a single set of braces, and getting errors.
From documentation The exterior set of curly braces are letting JSX know you want a JS expression. The interior set of curly braces represent a JavaScript object, meaning you're passing in a object to the style attribute.
The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. This process is generally referred to as "interpolation".
You probably shouldn't use inline styles if: You feel that you may move away from React or have components you need to share in non-React projects. You aren't willing to take on a new dependency in the form of an inline-styling library. You have a lot of global styling to maintain.
Setting Inline Styles in a React Component Specify the style object inside the constructor as follows. Notice here that the text-align CSS property got camel-cased to textAlign . Pass this styles object to the <H1 /> component, as shown below. Combine multiple style objects using the spread operator.
You're returning an object. So the outer {}
brackets are for returning a variable, and the inner {}
brackets are for creating an object.
Reformat it and it might make more sense:
style={
{
backgroundImage: `url(${avatarURL})`,
color: #ffffff,
fontSize: 16px
}
}
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