Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: why is double brace syntax, style{{..}}, required for inline styles

Tags:

reactjs

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.

like image 615
SherylHohman Avatar asked Dec 23 '17 07:12

SherylHohman


People also ask

Why are there double curly braces in React style?

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.

Why we use {} In React?

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

Why not use inline styles React?

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.

How do you add two inline styles in React?

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.


1 Answers

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
  }
}
like image 51
Brett DeWoody Avatar answered Oct 02 '22 01:10

Brett DeWoody