I recently spent some time playing with React, Facebook’s JavaScript framework for building user interfaces. The term “UI Framework” means different things to different people: In the case of React, it’s a framework that makes it easy to build and compose UI components; it is not a library of out-of-the-box UI components.
Some key characteristics of the React:
- No templates: Components are the building blocks. By keeping the markup and the corresponding UI logic together, you have the full power of JavaScript to express the UI. More on this here.
- JSX syntax allows you to inline the declarative description of the UI in your JavaScript code. React translates JSX to plain JavaScript on the fly (suitable during development), or offline using the React CLI.
- Virtual DOM. In React, rendering a component means creating a lightweight description of the component UI. React diffs this new description with the old one (if any), and generates a minimal set of changes to apply to the DOM.
The Sample App
Nothing like building an app to get familiar with a new language or framework. In this article, I share a React version of the Employee Directory app that I’ve used to explore other frameworks.
“Thinking in React” encourages us to start with a mockup of the UI, and break it down into a component hierarchy.
Based on this diagram, the component hierarchy for the Employee Directory app looks like this:
- App - HomePage - Header - SearchBar - EmployeeList - EmployeeListItem - EmployeePage - Header - EmployeeDetails
“App” is the application container that will transition pages in and out of the UI. Only one page is displayed at any given time.
Source Code
In this article, we will build the application going through several iterations, from a simple static prototype to the final product. The source code for the application, including the different iterations and a Cordova version, is available in this repository.
Iteration 1: Static Version
In this first version, we create and render the HomePage component with some hardcoded (static) sample data.
Code Highlights:
- Creating components is easy: You use React.createClass(), implement the render() function, and return the UI description.
- The JSX returned by render() is not an actual DOM node: it’s a description of the UI that will be diffed with the current description to perform the minimum set of changes to the DOM.
- JSX is optional: you can use the React APIs to create the UI description programmatically.
- Composing components is easy: You can use a component created using React.createClass() as a tag in JSX. For example, HomePage is made of three other components: Header, SearchBar, and EmployeeList.
Iteration 2: Data Flow
In this second version, we define an array of employees in the HomePage component, and we make the data flow down the component hierarchy to EmployeeList and EmployeeListItem. In this version, the list of employees is hardcoded: we’ll work with dynamic data in iteration 4.
Code Highlights:
- In JSX, you can add attributes to your custom component tags to pass properties to the component instance.
<EmployeeList employees={employees}/>
- Properties passed by the parent are available in this.props in the child. For example EmployeeList can access the list of employees provided by HomePage in this.props.employees.
- In a list component (like EmployeeList), it’s a common pattern to programmatically create an array of child components (like EmployeeListItem) and include that array in the JSX description of the component.
render: function () { var items = this.props.employees.map(function (employee) { return ( <EmployeeListItem key={employee.id} employee={employee} /> ); }); return ( <ul> {items} </ul> ); }
- The key attribute (like in EmployeeListItem above) is used to uniquely identify an instance of a component (useful in the diff process).
Iteration 3: Inverse Data Flow
In the previous version, the data flew down the component hierarchy from HomePage to EmployeeListItem. In this version, we make data (the search key to be specific) flow upstream, from the SearchBar to the HomePage where it is used to find the corresponding employees.
Code Highlights:
In this version, the inverse data flow is implemented by providing the child (SearchBar) with a handler to call back the parent (HomePage) when the search key value changes.
<SearchBar searchHandler={this.searchHandler}/>
Iteration 4: Async Data and State
In this version, we implement employee search using an async service. In this sample app, we use a mock in-memory service (defined in data.js) that uses promises so you can easily replace the implementation with Ajax calls. We keep track of the search key and the list of employees in the HomePage state.
Code Highlights:
- The state (this.state) is private to the component and is changed using this.setState().
- The UI is automatically updated when the user types a new value in SearchBar. This is because when the state of a React component is changed, the component automatically re-renders itself (by executing its render() function).
- getInitialState() executes once during the component lifecycle and and is used to set up the initial state of the component.
Iteration 5: Routing
In this version, we add an employee details page. Because the application now has more than one view, we add a simple view routing mechanism.
Code Highlights:
There are many options to implement routing. Some routing libraries are specific to React (check out react-router), but you can also use other existing routing libraries. Because the routing requirements of this sample app are very simple, I used a simple script (router.js) that I have been using in other sample apps.
- componentDidMount() is called when a component is rendered.
Iteration 6: Styling
Time to make the app look good. In this version, we use the Ratchet CSS library to provide the app with a mobile skin.
Code Highlights:
- Notice the use of className instead of class
Iteration 7: Maintaining State
If you run iteration 6, you’ll notice that when you navigate back to HomePage from EmployeePage, HomePage has lost its state (search key and employee list). In this version, we fix this problem and make sure the state is preserved.
Code Highlights:
To keep track of the state, we introduce a new parent container (App) that maintains the state (searchKey and employee list) of the Home page and reloads it when the user navigates back to the Home Page.
Running in Cordova
The react-cordova folder in the repository provides a preconfigured Cordova project for the React version of the Employee Directory application.
Pingback: 簡單玩 React | Duncan 's blog()
Pingback: Animated Page Transitions with React.js | Christophe Coenraets()
Pingback: Employee Directory Sample App with React and Node.js | Christophe Coenraets()
Pingback: Building Salesforce Apps with React.js | Christophe Coenraets()
Pingback: Belgian Beer Explorer with React, Bootstrap, Node.js and Postgres | Christophe Coenraets()
Pingback: About React | 懒得折腾()
Pingback: 久々にCordova (旧PhoneGap) 触ってみた | はなたんのブログ()
Pingback: 学习笔记 Cordova+AmazeUI+React 做个通讯录 – 准备 | Macworks Collection()
Pingback: ReactJS: Links And Resources (3) | Angel "Java" Lopez on Blog()
Pingback: Mobile Web Weekly No.35 | ENUE()
Pingback: 20 Resources and tutorials about ReactJS framework - JS-Republic's Blog()
Pingback: Free Online Tutorials To Learn ReactJS - Stunning Mesh()
Pingback: Native vs Hybrid App. Programming – butterflydroid()
Pingback: 10 Best ReactJS Tutorials With Examples()