Hello World with ReactJS – Code Example

0

This article represents code examples and high level concepts on React.js, a javascript library for building user interfaces, being developed by Facebook Engineers. The concepts shall be presented in detail in upcoming articles. Also, I would have to say that if you are a ReactJS expert and feel that there could be improvements with the code, please drop a line with suggestion and I shall update the article/code appropriately.

The demo of the code samples could be found on this page.

Before I go ahead and present some code samples, I have to make a mention that it was a little difficult to get started with React.js as I have been working a lot with AngularJS recently. By now, I would have to admit that they are significantly different in terms of way they help us do things with UI. I shall present another blog sighting key differences between them. However, at a high level, following are some of the reasons why I had a slightly steeper learning curve with ReactJS as well:

  • Component-oriented: It is component-oriented, meaning, it requires you to think UI elements as components. Interestingly, components are composable. This means that a component can have one or more inner component. This is demonstrated in the code below.
  • JSX Syntax: It uses an interesting JSX (XML-ish) syntax for writing the code. JXS transformer (a precompiler) is used to translate the syntax to the plain JavaScript.
  • Event Delegation Model: It follows the event delegation model to capture events.

Following are key concepts that are demonstrated in the code.

  • Components
  • Event delegation
  • JSX syntax

Following is brief of what is achieved along with components description

– There is an input element where users can enter their names. It is represented using “UserName” component later in the article.
– There is a div element which displays “Hello, username”. It is represented using “HelloText” component later in the article.

Following is how it is designed. Also, find the code representing the below concepts.

 

SayHello: Composable Component

SayHello is a Parent component that includes following two components. This is the parent component comprising of two inner components. One of the component is UserName which is used to allow user to enter their name and other component is HelloText which displays the text such as Hello, World. It defines following three different APIs:

  • getInitialState
  • handleNameSubmit
  • render (This is a MUST and a component needs to define it to tell React how to render the component).
 //
      // This is the parent component comprising of two inner components
      // One of the component is UserName which is used to allow user to enter their name
      // Other component is HelloText which displays the text such as Hello, World
      //
      var SayHello = React.createClass({
        // This is used to set the state, "data" which is 
        // accessed later in HelloText component to display the updated state
        // 
        getInitialState: function() {
          return {data: 'World'}
        },
        // It is recommended to capture events happening with any children
        // at the parent level and set the new state that updates the children appropriately
        handleNameSubmit: function(name) {
          this.setState({data: name});
        },
        // Render method which is comprised of two components such as UserName and HelloText
        //
        render: function() {
         return(
           <div>
            <UserName onNameSubmit={this.handleNameSubmit}/>
            <HelloText data={this.state.data}/>
           </div>
           );
        }
      });

 

UserName Component

UserName component has following two methods:

  • handleChange: Used to capture onChange event
  • render: Code to render the component
var UserName = React.createClass({
        handleChange: function() {
          var username = this.refs.username.getDOMNode().value.trim();
          this.props.onNameSubmit({username: username });
          this.refs.username.getDOMNode().value = '';
          return false;
        },
        render: function() {
         return(
          <form role="form" onChange={this.handleChange}>
             <div className="input-group input-group-lg">
                <input type="text" className="form-control col-md-8"  placeholder="Type Your Name" ref="username"/>
             </div>
          </form>
          );
        }
      });

 

HelloText Component

HelloText component has just one method for rendering the component:

  • render: Consists of code display the HelloText component
var HelloText = React.createClass({
          render: function() {
            return (
            <div>
              <h3>Hello, {this.props.data}</h3>
            </div>
            );
          }
      });

If you would like to get a quick hold on entire code, I have put it up on this github hello-reactjs page. Feel free to comment/suggest.

[adsenseyu1]

Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, C/C++, mobile programming languages etc, and, computing fundamentals related with cloud-native technologies, application security, cloud computing platforms, mobile apps, big data etc.

He has also authored the book, Building Web Apps with Spring 5 and Angular.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.