Getting started with facebook react with instant search sample program

Couple of months ago facebook open sourced their framework named React when it reached to a stable version. React is very much different than the other javascript frameworks like ember, angular, backbone and all. So before start developing your first React application, you must know the following points.

  1. React is not MVC.
  2. React follows component based architecture.
  3. It doesn’t use templates.

Objective

Today’s objective is to make an instant search using the react framework. While doing this, we will use the immutable property bags ‘props’, ‘state’ and also ‘ref’. Data binding is another important feature which we will use here to make this instant search.

We will call the component ‘InstantBox’. The InstantBox will have two more components inside it. First one is SearchBox, which will actually be the search text input and DisplayTable, which will display the eligible data.

The diagram below describes the flow of the application.

react instant search

Let’s take the first step

React uses JSX. (Though you can use normal javascript also, but JSX is a better option in case of React).

To start, you include the React framework and the JSX library in your project. You can directly download the starter kit and include the react.js and JSXTransformer.js. Or you can directly start your development in React JsFiddle page.

<script src="lib/react.js"></script>
<script src="lib/JSXTransformer.js"></script>

Once you do that, you are ready to write the code for your first React application.

What is ‘props’ and ‘state’

Before start writing the code let me tell you what is ‘props’ and ‘state’ in React components. These are property bags. You can store your variables in a default object called ‘state’. All the bindings in react have to be done through state. That means you only can do data binding with the variables that are inside your ‘state’.

‘Props’ is another property bag which contains the properties given to a component by its parent. In today’s example of us we will use these property bags, so after going through the whole article you will be well able to understand these two things and also how to use them.

Make your first component

First we will make the SearchBox component. In our case this is the most small and simple one. A component always has a function inside it named ‘render’. This is the function which renders the component to the DOM. So let’s see how to make the component.

var SearchBox = React.createClass({
	doSearch:function(){
		var query=this.refs.searchInput.getDOMNode().value; // this is the search text
		this.props.doSearch(query);
	},
	render:function(){
		return <input type="text" ref="searchInput" placeholder="Search Name" value={this.props.query} onChange={this.doSearch}/>
	}
});

As you can see, the render function returns an html input, with an attribute ref=”searchInput” which is sort of using an id.  onChange={this.doSearch} means on any text change in the input the doSearch() function of the component. value={this.props.query}, here comes the data binding in picture. The ‘value’ is binded with the external property (provided by parent or from somewhere outside, at the time of rendering).

In the function doSearch() we’ve stored the input value in the variable named query. Well, one thing I would like to tell you, in case of react data flows only in one direction; that is, parent to child. So the automatic data binding in possible from parent to child, not vice versa. So that’s why we’ve stored the value of the input in the variable named query and passed that to a function of parent, which is provided to our SearchBox through the ‘props’ bag.

This.props.doSearch() is a function which is provided to SearchBox component externally. We will see how to provide variables and functions using the ‘props’ when we will make our InstantBox component.

DisplayTable component to display data

DisplayTable is another component of us which will just display the data provided to it. We will filter out the data according to the query in our InstantBox component and will provide the filtered data to DisplayTable via ‘props’ and it will just display the data in a particular format.

var DisplayTable = React.createClass({
	render:function(){
		//making the rows to display
		var rows=[];
		this.props.data.forEach(function(person) {
		rows.push(<tr><td>{person.name}</td><td>{person.roll}</td></tr>)
		});
		//returning the table
		return(
			 <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Roll No</th>
                    </tr>
                </thead>
                <tbody>{rows}</tbody>
            </table>
		);
	}
});

This component just renders a table with given data. There’s not much thing to explain.

InstantBox: The container component

Before start coding for our main component ‘InstantBox’, let’s see what is ‘state’ and how it works.

State is an inbuilt property bag of the react components. You can initialize any variable inside the state using the default function getInitialState(). You also can set new values to your state properties which will led to automatic data binding.

var InstantBox = React.createClass({
	doSearch:function(queryText){
		console.log(queryText)
		//get query result
		var queryResult=[];
		this.props.data.forEach(function(person){
			if(person.name.toLowerCase().indexOf(queryText)!=-1)
			queryResult.push(person);
		});

		this.setState({
			query:queryText,
			filteredData: queryResult
		})
	},
	getInitialState:function(){
		return{
			query:'',
			filteredData: this.props.data
		}
	},
	render:function(){
		return (
			<div className="InstantBox">
				<h2>Void Canvas Instant Search</h2>
				<SearchBox query={this.state.query} doSearch={this.doSearch}/>
				<DisplayTable data={this.state.filteredData}/>
			</div>
		);
	}
});

So we are using two variables, named ‘query’ and ‘filteredData’ in our state. The variable are accessible as this.state.query and this.state.filteredData; and they are initialized using the getInitialState() function.

We also have a function name ‘doSearch’ which accepts a parameter and filter out data and sets the filteredData state property. The ‘props.data’ of InstantBox will be provided while rendering the component to our main html.

Now have a look at the render function of InstantBox. It has a div with className as its own name and two child components who are no one else but our SearchBox and DisplayTable.

So, here while rendering SearchBox we’re providing the property ‘query’ as {this.state.query}. So now the ‘query’ property of ‘state’ of ‘InstatBox’ is accessible from ‘SearchBox’ as ‘props.query’. Same happens with ‘doSearch’. So now I think the ‘props’ property bag is clear to you.

In case of rendering ‘DisplayTable’, we’re passing the ‘filteredData’, the state variable of ‘InstantBox’ as a property names ‘data’.

Time for final touch

Now as all those three components are ready, we just have two remaining works. First one is to render the ‘InstantBox’ to our html and provide data to the component.

React.renderComponent(<InstantBox data={tableData}/>,document.body);

Above is the code to render a component to your html. We’re also providing data from an external variable called ‘tableData’ which is nothing but an array of objects. Below is how ‘tableData’ variable is defined.

var tableData=[
{
	name:'Paul Shan',
	roll: '001'
},
{
	name:'John Doe',
	roll: '002'
},
{
	name:'Sachin Tendulkar',
	roll: '003'
}];

So now your code is ready to run. You can view the running code clicking on the Live Demo button below. You can also download the source and analyze the code.

Important things to know

JSX doesn’t run locally in most of the browsers. So to run JSX you have to upload your file to a server. You can also use servers like ‘wamp’ to run the files from your computer.

Before starting the JSX code you have to write the following comment.

 /**
   * @jsx React.DOM
 */

live-demo-button download-button


Still having issues?

If you still have issues understanding the above article, please leave a comment below and we will try to address that. In case you need help in your projects or understanding anything related to Programming; contact me, Paul Shan for assistance. Thank you for being a reader of VoidCanvas.

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.

  • Great post. Can you do a tutorial for Ruby on Rails?

  • Dhara

    I have a doubt.. if I want to add a new label in list during searching in input box.. then it doesn’t update the initial list and shows suggested list as a main list.. what I need is on adding a new element update list and shows original whole list.. can u tell me how to do?

    • Paul Shan

      Your question is not very much clear to me. Do you want two list.. one displaying the original list always and second one the way we have the list already? If yes, then adding in InstantBox’s render function will solve the issue. Lemme know if your requirement is something else.

    • Dhara

      Its somewhat different..exactly like ur demo.. but have add button after input text also can add new values..what I need is after adding new value list doesn’t update it shows suggestion list only

    • Paul Shan

      You want an “Add” button, clicking on which, a new element will be inserted in the main list using the text/value of the inbutBox. And from next search, the filtered list will consider the newly added element too. Is this your requirement?

    • Dhara

      yes exactly..

    • Paul Shan

      First add the button element below in InstantBox render()

      
      Add this
      

      Now add the addToList function in InstantBox.

      
      addToList(){
      		var query=this.state.query;
      		this.props.data.push({
      			name: query,
      			roll: "NA"
      		});
      		this.doSearch(query);
      	},
      

      Lemme know if it solves your problem!

    • Dhara

      Thanks! I will try 🙂