In the following:
<div style={{marginTop:'10%'}}>
do I read this as style is an object (the outer {}) that contains an array (the inner {}) ?
In the following:
<div style={{marginTop:'10%'}}>
do I read this as style is an object (the outer {}) that contains an array (the inner {}) ?
In JSX, everything gets wrapped in curly braces {}
. When you see a set of {}
, then you know that what's inside of them is JavaScript. For the style prop, it accepts an object. So your style is {marginTop: '10%'}
and it's wrapped in JSX {}
. You could also write it as this:
const customStyle = { marginTop: '10%' };
<div style={customStyle}></div>
The {}
just let React know that you are using JavaScript instead of a string.
The outer {}
indicate that the value of the attribute is an expression to be evaluated, rather than a static string. (You never use static strings with the style
attribute in React; you can with other attributes.) The content of the expression is any valid JavaScript expression; in this case, an object initializer defining an object with a property called marginTop
with a value '10%'
. (This is how you set the style
of an element in React: Via an object.) There are no arrays in the example.
I suggest working through the Intro to React tutorial to get the lay of the land.
There are two different languages intermixed here.
The outer language is JSX. It's the part that resembles HTML, but compiles to Javascript. The outer {} is part of the JSX syntax, meaning "what's inside is Javascript".
The inside of the expression constructs a Javascript object. That syntax also uses the brace, enclosing a set of key-value pairs. That object is interpreted as a style.
Within the outer braces, you can use any Javascript expression. So you could write your method as:
render() {
const style = {marginTop:'10%'};
return <div style={style}>;
}
This is a Javascript method, which returns an object created in JSX, containing a reference to the style
value created in Javascript.
Technically it's all one language, JSX being a superset of Javascript, but I think it's helpful to describe the extensions as JSX and the regular part as just Javascript.
It is read as an object (inner {}
) containing one property marginTop
passed as a property do a div element via outer {}
.