Wednesday, 30 December 2015

ReactJS simple example

The best way to learn a new Javascript library is to write a simple bare-bones example. In this post I have a written a simple ReactJS example that displays the classic ‘Hello World’ message.

Firstly, we have our basic HTML5 structure including a div tag with the id ‘container’. The external Javascript files included are: the React library itself, and the React-dom library which provides the DOM specific methods. The empty script tag is where we will add the ReactJS code.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>React Example</title>
</head>
<body>
<div id=“container”></div>
<script src="https://fb.me/react.js"></script>
<script src="https://fb.me/react-dom.js"></script>

<script>
//Code goes here
</script>

</body>
</html>

Inside of the empty script tag add the following code below. React is built on the idea of components. Essential everything in a React app is part of a component. Our main component in the example is the App component.

A component is created using the createClass method. Every React component must have a render() method which states the HTML to be added to the page. The ReactDOM render() method adds the content from the App component to the div with the id ‘container’. The first argument is the App component and the second argument is a reference to the div.

var App = React.createClass({
  render:function(){
    return (
      <div>
      <p>Hello World</p>
      </div>
    );
  }
});
ReactDOM.render(<App />, document.getElementById('container')); 

You may have noticed the HTML content is inside the Javascript code. This is not official HTML, but is a new React concept called JSX which is basically a Javascript extension that allows you to write XML style tags. At runtime the HTML and Javascript get added to the DOM together.

We can also nest multiple components inside of the App component. In the following example I have created a ‘Hello World’ Component and added two instances inside of the App component.

var HelloWorld = React.createClass({
  render:function(){
    return (
      <p>Hello World</p>
    )  
  }
});

var App = React.createClass({
  render:function(){
    return (
      <div>
        <HelloWorld />
        <HelloWorld />
      </div>
    );
  }
});

ReactDOM.render(<App />, document.getElementById('container')); 

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP