Building a simple component in React.js - Part 3 - Displaying Results


In the last post we carried on building some React.js components for searching for a company name and displaying matching names. In this post, we are going to finish this off by displaying the results.

The first thing we need to do is to complete the implementation of the handleSearch function in the Search component.

  • Line 2 initialises some state that we use for the matching customers
  • Line 46 calls a new getCustomers function, which loops through the customers array, checking for matches, builds up an array of matching customers, before returning the built up array
  • Line 47 sets some state to the matching customers
  • Line 53 passes that state into the Results component. When state changes, the Results component will automatically be re-rendered
var Search = React.createClass({
getInitialState: function() {
return { data: [] };
},
customers: [
{
name: "Alfreds Futterkiste"
},
{
name: "Berglunds snabbköp"
},
{
name: "Cactus Comidas para llevar"
},
{
name: "Chop-suey Chinese"
},
{
name: "Du monde entier"
},
{
name: "Ernst Handel"
},
{
name: "France restauration"
},
{
name: "Island Trading"
},
{
name: "Let's Stop N Shop"
},
{
name: "Maison Dewey"
},
{
name: "Paris spécialités"
},
{
name: "Que Delícia"
},
{
name: "Rancho grande"
}
],
getCustomers: function(criteria) {
var i,
ret = [];
for (i = 0; i < this.customers.length; i = i + 1) {
if (this.customers[i].name.toLowerCase().indexOf(criteria) === 0) {
ret.push(this.customers[i]);
}
}
return ret;
},
handleSearch: function(criteria) {
var i, ret;
ret = this.getCustomers(criteria);
this.setState({ data: ret });
},
render: function() {
return (
<div>
<Criteria onSearch={this.handleSearch} />
<Results data={this.state.data} />
</div>
);
}
});

Lastly, we need to change the Results component.

  • Line 3 interates over the data property we passed into the component (our matching customers) and builds up a list of customer names
  • Line 13 returns the list markup
  • Notice on line 13 you need to pass in the inline style attribute as an object or React.js complains
var Results = React.createClass({
render: function() {
var listItems = this.props.data.map(function(customer) {
return <li>{customer.name}</li>;
});
var listStyle = {
listStyleType: "none",
padding: "0"
};
return <ul style={listStyle}>{listItems}</ul>;
}
});

That completes our components. The full markup can be found here

Recommended reading for building great React apps:

Learn React with TypeScript - 3rd Edition

New

A comprehensive guide to building modern React applications with TypeScript. Learn best practices, advanced patterns, and real-world development techniques.

View on Amazon
Learn React with TypeScript - Third Edition