React Tutorials — Hello World with attributes

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

This is continuation of tutorial

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


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

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”);


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

For a complete list of attributes supported please check

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

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

JS Bin
Go here and play around with the working example. Inspect the element to check the generated attributes.