Friday, July 17, 2015

An overview of ReactJS with JSX for dynamic UI generation

The last couple of weeks that passed by was a hell of a busy time with so many submissions, assignments and evaluations at the university. Yet one very interesting happened on the 3rd of July.
"Yaaay! I passed the mid evaluations!!!"
I am glad I got through it some how. The work that was assigned to be completed before the mid term evaluations was to complete the unified search and browse functionality for a single entity. What I chose was 'Artist'. My mentor wanted to see some outcome in the working state even if all the details aren't looked into. So I focused and narrowed my work to the fields Type, Gender and Tag.

Since I could not mention about ReactJS in any of the previous posts here it goes...



Apparently what I used for the UI generation of this interface was ReactJS. I had never heard of React any time before I started working on this interface but luckily I could get hold of its concepts within almost a week.

ReactJS basically allows one to look at and organize a web interface in a sense of components that are arranged in a hierarchical manner. The key powerful thing it provides is the ability to incorporate a state to each of those components so that a dynamic change to the web interface is made as simple as setting the value of some variable in JavaScript. A change to the state of the component automatically triggers the UI of the component to be refreshed and re rendered. Changes to the state may happen in many possible ways including an action from the user. This action in almost all the cases can be considered as an event.

Another interesting thing I came across with ReactJS is JSX. JSX is basically an object oriented programming language that can be used with React to create that component hierarchy I mentioned earlier about. The JSX syntax basically resembles that of XML and makes it pretty easy to understand what that code does with the UI. Say we have a React component named 'Results' and the tag
<Results />
will magically output what ever HTML or JSX that was specified in the render method of that particular component. This ought to give you some idea on how the hierarchy happens too. If it was some JSX tags that were specified in the render method, what we have is a nested component inside another component. The following example will help with any confusions.

var DateInput = React.createClass({
  render: function () {
    return (
      <div>
        <span className="partial-date">
          <input maxLength="4" placeholder='YYYY' size="4" className="partial-date-year" />
          -
          <input maxLength="2" placeholder='MM' size="2" className="partial-date-month" />
          -
          <input maxLength="2" placeholder='DD' size="2" className="partial-date-day" />
        </span>
      </div>
    );
  }
});

var ValidString = React.createClass({
  render: function () {
    return (
      <div><span>'Please enter a valid input.'</span></div>
    );
  }
});

var DateRangeField = React.createClass({
  render: function () {
    return (
      <div>
        <h3>From</h3>
        <DateInput />
        <h3>To</h3>
        <DateInput />
        <ValidString />
      </div>
    );
  }
});



As shown above each react component will have its own render function which specifies its contribution to the UI. Above 3 classes are the simplest form where none of them have any state incorporated to them. What I intended on emphasizing here is the fact that the components DateInput and ValidString are enclosed in the DateRangeField and
React.render(DateRangeField, document.getElementById("content"));
would render the built hierarchy into HTML as follows.

<div>
  <h3>From</h3>
  <div>
    <span className="partial-date">
      <input maxLength="4" placeholder='YYYY' size="4" className="partial-date-year" />
      -
      <input maxLength="2" placeholder='MM' size="2" className="partial-date-month" />
      -
      <input maxLength="2" placeholder='DD' size="2" className="partial-date-day" />
    </span>
  </div>
  <h3>To</h3>
  <div>
    <span className="partial-date">
      <input maxLength="4" placeholder='YYYY' size="4" className="partial-date-year" />
      -
      <input maxLength="2" placeholder='MM' size="2" className="partial-date-month" />
      -
      <input maxLength="2" placeholder='DD' size="2" className="partial-date-day" />
    </span>
  </div>
  <div><span>'Please enter a valid input.'</span></div>
</div>


The following component demonstrate the use of function call backs on event triggers.

var SearchBox = React.createClass({
  handleTextInput: function (event) {
    if (event.keyCode === 13) {
      var input = event.target.value;
      console.log(input);
    }
  },

  render: function () {
    return (
      <input id="search-box" type="text" onKeyDown={this.handleTextInput} />
    );
  }
});


the onKeyDown={this.handleTextInput} property specied in the input tag tells React to execute the handleTextInput method defined above it when ever a keydown event fires. The SyntheticEvent object that corresponds to the event that occurred will automatically be passed into the function when it is being called without the user explicitly needing to specify it.

The following component I have built demonstrates the use of the state of a component to decide whether a part of its render method HTML code needs to be visible on the UI or not.

var Panel = React.createClass({
  getInitialState: function () {
    return {collapseState: false};
  },

  handleTitleClick: function (event) {
    event.preventDefault();
    this.setState({collapseState: !this.state.collapseState});
  },

  render: function () {
    return (
      <div>
        <div className="panel-heading" id="headingOne">
          <div className="panel-title">
            <a href="#" id={"title-artist"} onClick={this.handleTitleClick}>
              Artist
            </a>
          </div>
        </div>
        {this.state.collapseState &&
          <div id={"collapse-artist"} className="panel-collapse" >
            Visible/ Invisible Artist Content
          </div>
        }
      </div>
    );
  }
});

Using the '&&' operator is a simpler way of saying 'display the one after it only when the expression prior to it evaluates to true'. So what this component basically does is clicking on the <a> hyperlink would fire the event flipping the value of the state variable collapseState there by toggling the visibility of the "collapse-artist" div.

Another useful feature in React is the ability to pass properties to the child components in the hierarchy when they are specified in JSX. For example say there is a component named Content. When we specify that component using JSX anywhere, we have the ability to pass it any properties of any types we like.
<Content property1="This is property string" property2={prop: "This is property ob"} /> All these property values can be accessed inside the Content component simply by referring them as
this.props.property1 which will return the string and this.props.property2 which will return the object.

This is some basic overview on what ReactJS can do. The React documentation has all these plus many more other things looked much deeper into depth. One thing is for sure... I am in love with ReactJS!

Ruchiranga Wickramasinghe

Author & Editor

Computer Science Master's Student at EPFL, Switzerland

1 comments :

  1. Great blog post. You have very in-depth knowledge on React. Keep learn more about React and Write master piece article like this.

    Best Regards,
    ReactJS Online Training in India-CourseIng

    ReplyDelete

Find me on

LinkedIn Google+
Twitter Facebook
Ruchiranga Wickramasinghe | Create Your Badge