Defining Attributes/Props in JSX
In the previous chapter, section 4.4, I discussed passing React.createElement(type, props, children)
attributes/props when defining React nodes. Since JSX is transformed into React.createElement()
function calls you basically already have a understanding of how React node attributes/props work. However, since JSX is used to express XML-like nodes that get turned into HTML, attribute/props are defined by adding the attributes/props to JSX expressions as name-value attributes.
In the code example below I am defining a React <li>
element node, using JSX, with five attributes/props. One is a non-standard HTML attribute (e.g., foo:'bar'
) and the others are known HTML attributes.
var styles = {backgroundColor:'red'};
var tested = true;
var text = 'text';
var reactNodeLi = <li id=""
data-test={tested?'test':'false'}
className="blue"
aria-test="test"
style={styles}
foo="bar">
{text}
</li>;
ReactDOM.render(reactNodeLi, document.getElementById('app1'));
The JSX when it is transformed will look like this (note that attributes/props just become arguments to a function):
var reactNodeLi = React.createElement(
'li',
{ id: '',
'data-test': tested ? 'test' : 'false',
className: 'blue',
'aria-test': 'test',
style: styles,
foo: 'bar' },
text
);
When the reactNodeLi
node is render to the DOM it will look like this:
<div id="app1">
<li id="true"
data-test="test"
class="blue"
aria-test="test"
style="background-color:red;"
data-reactid=".0">
text
</li>
</div>
You should note the following:
- Leaving an attribute/prop blank results in that attribute value becoming true (e.g.,
id=""
becomesid="true"
andtest
becomestest="true"
) - The
foo
attribute, because it was not a standard HTML attribute, doesn’t become a final HTML attribute.
Notes
- If an attribute/prop is duplicated the last one defined wins.
- If you pass props/attributes to native HTML elements that do not exist in the HTML specification, React will not render them. However, if you use a custom element (i.e., not a standard HTML element) then arbitrary/custom attributes will be added to custom elements (e.g.,
<x-my-component custom-attribute="foo" />
). - Omitting the value of an attribute/prop causes JSX to treat it as true (i.e.,
<input checked id type="checkbox" />
becomes<input checked="true" id="true" type="checkbox">
). This will even occur for attributes/props that are not presented in the final HTML due to the fact they are not actual HTML attributes. - The
class
attribute has to be writtenclassName
- The
for
attribute has to be writtenhtmlFor
- The
style
attribute takes a reference to an object of camel-cased style properties - HTML form elements (e.g.,
<input></input>
,<textarea></textarea>
, etc.) created as React nodes support a few attributes/props that are affected by user interaction. These are:value
,checked
, andselected
. - React offers the
key
,ref
, anddangerouslySetInnerHTML
attributes/props that don’t exist in DOM and take on a unique role/function. - All attributes are camel-cased (e.g.,
accept-charset
is written asacceptCharset
) which differs from how they are written in HTML. - The following are the HTML attributes that React supports (shown in camel-case):
accept acceptCharset accessKey action allowFullScreen allowTransparency alt
async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge
charSet checked classID className colSpan cols content contentEditable
contextMenu controls coords crossOrigin data dateTime default defer dir
disabled download draggable encType form formAction formEncType formMethod
formNoValidate formTarget frameBorder headers height hidden high href hrefLang
htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label
lang list loop low manifest marginHeight marginWidth max maxLength media
mediaGroup method min minLength multiple muted name noValidate nonce open
optimum pattern placeholder poster preload radioGroup readOnly rel required
reversed role rowSpan rows sandbox scope scoped scrolling seamless selected
shape size sizes span spellCheck src srcDoc srcLang srcSet start step style
summary tabIndex target title type useMap value width wmode wrap