React javascript render hello world

React render can be written purely in Javascript without jsx. For JSX version of this tutorial you can visit React jsx hello world. Here is javascript version of same tutorial (without jsx).

React javascript render – using React.createElement

Here we are not setting any element properties (null).

<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>

<div id="hello"></div>

<script type="text/javascript">
ReactDOM.render(React.createElement(
  'h1',
  null,
  'Hello world'
), document.getElementById('hello'));
</script>
refresh

React javascript render – set className property

Here we will set className in properties argument.

<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>

<style type="text/css" media="screen">
.foo {background-color:lightgreen;} 
</style>
<div id="hello"></div>

<script type="text/javascript">
ReactDOM.render(React.createElement(
  'h1',
  {className:"foo"},
  'Hello world'
), document.getElementById('hello'));
</script>
refresh

React javascript render – using factory React.DOM.h1

Note that React.DOM.h1 is a built in factory which creates component h1 for us.

<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>

<div id="hello"></div>

<script type="text/javascript">
ReactDOM.render(React.DOM.h1(
  null,
  'Hello world'
), document.getElementById('hello'));
</script>
refresh

Few points to note

  1. If you inspect hello world element in Chrome, here is how the dom element looks like.
    react-javascript-render-hello-world-inspect-dom
  2. Babel javascript compiler is not needed here as there is no jsx.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments