Building a simple component in React.js - Part 2 - Search Event
September 29, 2015
react
In the last post we started building some React.js components for searching for a company name and displaying matching names. In this post, we are going to handle the search request before displaying the results in the final post.
The first thing we need to do is change the Criteria component to handle a click event on the button.
- Line 13 creates a click event on the “Go” button that is handled by a handleClick function
- In the handleClick function, line 5 gets the search criteria from the search box
- Line 6 sets a “onSearch” property to the criteria that the parent component can pick up on
var Criteria = React.createClass({
handleClick: function(e) {
var criteria;
e.preventDefault();
criteria = React.findDOMNode(this.refs.search).value.trim();
this.props.onSearch(criteria);
},
render: function() {
return (
<div>
<input ref="search" type="search" placeholder="Search criteria" />
<button onClick={this.handleClick}>Go</button>
</div>
);
}
});
The next thing to do is to wire up the onSearch property in the Search component and react to it.
- Line 9 wires the onSearch property in the instance of the Criteria component to the handleSearch function
- For now, the implementation of the handleSearch function is to simply output the search critieria to the console. We will expand on this in our next post
var Search = React.createClass({
handleSearch: function(criteria) {
console.log(criteria);
// TODO
},
render: function() {
return (
<div>
<Criteria onSearch={this.handleSearch} />
<Results />
</div>
);
}
});
Here’s the code for all our components and the consuming page at this point:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Search for a company</h1>
<div id="app"></div>
<script src="https://fb.me/react-0.13.3.min.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script type="text/jsx">
var Criteria = React.createClass({
handleClick: function (e) {
var criteria;
e.preventDefault();
criteria = React.findDOMNode(this.refs.search).value.trim();
this.props.onSearch(criteria);
},
render: function () {
return (
<div>
<input ref="search" type="search" placeholder="Search criteria" />
<button onClick={this.handleClick}>Go</button>
</div>
)
}
});
var Results = React.createClass({
render: function () {
return (
<ul>
<li>test 1</li>
<li>test 2</li>
</ul>
);
}
});
var Search = React.createClass({
handleSearch: function (criteria) {
console.log(criteria);
// TODO
},
render: function () {
return (
<div>
<Criteria onSearch={this.handleSearch} />
<Results />
</div>
)
}
});
React.render(<Search />, document.getElementById("app"));
</script>
</body>
</html>
If you to learn about using TypeScript with React, you may find my course useful:
Using TypeScript with React
You might find some of my other posts interesting: