React Tutorials — Hello World with attributes

Pankaj Bhageria
Learn React
Published in
2 min readNov 29, 2015

In this tutorial we will learn how to render attributes of an html element.

This is continuation of tutorial

https://medium.com/@panbhag/react-tutorials-01-hello-world-d1b61d27d5bd#.ha29rhvz6

Every html element can have different attributes, like id, class, value, name etc.

React.createElement(elementName,[options],[children])

The second parameter of React.createElement accepts options which are the attributes of the element. The keys are the attributes names and the values are the values of attributes. The name of the keys are same as the generated attribute names, except for few cases which will see later in the article

So lets say we want to add an id attribute to the hello world element.

var element = React.createElement(“div”,{id:"greeting"},”Hello World”);

Now lets render the element

React.render(element, document.getElementById(“container”) )

This will generate the div element with id attribute as shown

<div id="greeting" >
Hello World
</div>

Now lets say we have to add an attribute “class” to our element. Now as class is a reserved keyword, so we cannot use it. We have to use “className” instead. The generated code will have attribute “class”.(Note that generated code will be html, class is a keyword in JavaScript). The other list of attributes for which you have to use alternative name is “for”. Use “htmlFor” instead.

so code to add id “greeting” and class “message” would be.

var element = React.createElement(“div”,{id:"greeting",className:"message"},”Hello World”);

generates

<div id="greeting" class="message" >
Hello World
</div>

For a complete list of attributes supported please check https://facebook.github.io/react/docs/tags-and-attributes.html)

So to summarize the rules for attributes:

  1. all valid attributes are supported and are camel cased. So html attributes like radiogroup, readonly,colspan,minlength will be radioGroup, readOnly, colSpan, minLength respectively. For complete list see the the above reference link.
  2. for class the name is className and “for” is “htmlFor”
  3. all data-* and aria-* attributes are in same format.

Finally Lets add two more attributes “contentEditable” and a “data-*” attribute to our div

var element = React.createElement(“div”,{id:"greeting",className:"message",contentEditable:true,data-something:"12"},”Hello World”);

which after rendering gives

<div id=”greeting” class=”message” contenteditable=”true” data-something=”123"> Hello World</div>

The full working example discussed in this article can be found at.

--

--

Pankaj Bhageria
Learn React

programmer, meditator, likes to teach and help,believes in keeping things simple