Building a simple component in React.js - Part 1 - Intro and Basic UI
In the next 3 posts, we’re going to build search and results components using React.js. The components will allow you to search for a company name and the matching names will be displayed beneath the search box.
The components will look like below. There will be 3 components:
- Criteria. The search textbox and “go” button
- Results. The list of results
- Search. The overall component - the parent of Criteria and Results
Consuming page
The html of the consuming page is listed below.
- Line 10 is a placeholder for where the components will be injected
- Line 12 is a reference to React.js
- Line 13 is a reference to the React library that will transform the JSX in our components into valid HTML / JS
- Line 15 is a placeholder for where we are going to write our React components
<!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">
// TODO
</script>
</body>
</html>
Creating our 3 basic components
You create a component in React.js by calling React.createClass(). The key function within a React component, that you must implement, is render() which should return the JSX for the component - JSX is a lot like HTML.
In the code below, we create our 3 component classes, returning the basic JSX we need.
- Line 24 defines the outer component referencing the sub components, Criteria and Results
- Line 2 defines the Criteria component
- Line 13 defines the Results component with some hardcoded results at this point
- Line 35 is where we tell React to inject the outer component, Search, into the DOM node with id “app”
<script type="text/jsx">
var Criteria = React.createClass({
render: function () {
return (
<div>
<input ref="search" type="search" placeholder="Search criteria" />
<button>Go</button>
</div>
)
}
});
var Results = React.createClass({
render: function () {
return (
<ul>
<li>test 1</li>
<li>test 2</li>
</ul>
);
}
});
var Search = React.createClass({
render: function () {
return (
<div>
<Criteria />
<Results />
</div>
)
}
});
React.render(<Search />, document.getElementById("app"));
</script>
In subsequent parts we will build on these component implementations …
If you to learn about using TypeScript with React, you may find my course useful: