Advanced React Components

The chapter will focus on the implementation of advanced React components. You will learn about higher order components and how to implement them. In addition you will dive into more advanced topics in React and implement complex interactions with it.

Ref a DOM Element

Sometimes you need to interact with your DOM nodes in React. The ref attribute gives you access to a node in your elements. Usually that is an anti pattern in React, because you should use its declarative way of doing things and its unidirectional data flow. You have learned about it when you have introduced your first search input field. But there are certain cases where you need access to the DOM node. The official documentation mentions three use cases:

  • to use the DOM API (focus, media playback etc.)
  • to invoke imperative DOM node animations
  • to integrate with third-party library that needs the DOM node (e.g. D3.js)

Let’s do it by example with the Search component. When the application renders the first time, the input field should be focused. That’s one use case where you would need access to the DOM API. This chapter will show you how it works, but since it is not very useful for the application itself, we will omit the changes after the chapter. You can keep it for your own application though.

In general, you can use the ref attribute in both functional stateless components and ES6 class components. In the example of the focus use case, you will need a lifecycle method. That’s why the approach is first showcased by using the ref attribute with an ES6 class component.

The initial step is to refactor the functional stateless component to an ES6 class component.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. class Search extends Component {
  3. render() {
  4. const {
  5. value,
  6. onChange,
  7. onSubmit,
  8. children
  9. } = this.props;
  10. return (
  11. # leanpub-end-insert
  12. <form onSubmit={onSubmit}>
  13. <input
  14. type="text"
  15. value={value}
  16. onChange={onChange}
  17. />
  18. <button type="submit">
  19. {children}
  20. </button>
  21. </form>
  22. # leanpub-start-insert
  23. );
  24. }
  25. }
  26. # leanpub-end-insert

The this object of an ES6 class component helps us to reference the DOM node with the ref attribute.

{title=”src/App.js”,lang=javascript}

  1. class Search extends Component {
  2. render() {
  3. const {
  4. value,
  5. onChange,
  6. onSubmit,
  7. children
  8. } = this.props;
  9. return (
  10. <form onSubmit={onSubmit}>
  11. <input
  12. type="text"
  13. value={value}
  14. onChange={onChange}
  15. # leanpub-start-insert
  16. ref={(node) => { this.input = node; }}
  17. # leanpub-end-insert
  18. />
  19. <button type="submit">
  20. {children}
  21. </button>
  22. </form>
  23. );
  24. }
  25. }

Now you can focus the input field when the component mounted by using the this object, the appropriate lifecycle method, and the DOM API.

{title=”src/App.js”,lang=javascript}

  1. class Search extends Component {
  2. # leanpub-start-insert
  3. componentDidMount() {
  4. if(this.input) {
  5. this.input.focus();
  6. }
  7. }
  8. # leanpub-end-insert
  9. render() {
  10. const {
  11. value,
  12. onChange,
  13. onSubmit,
  14. children
  15. } = this.props;
  16. return (
  17. <form onSubmit={onSubmit}>
  18. <input
  19. type="text"
  20. value={value}
  21. onChange={onChange}
  22. ref={(node) => { this.input = node; }}
  23. />
  24. <button type="submit">
  25. {children}
  26. </button>
  27. </form>
  28. );
  29. }
  30. }

The input field should be focused when the application renders. That’s it basically for using the ref attribute.

But how would you get access to the ref in a functional stateless component without the this object? The following functional stateless component demonstrates it.

{title=”src/App.js”,lang=javascript}

  1. const Search = ({
  2. value,
  3. onChange,
  4. onSubmit,
  5. children
  6. }) => {
  7. # leanpub-start-insert
  8. let input;
  9. # leanpub-end-insert
  10. return (
  11. <form onSubmit={onSubmit}>
  12. <input
  13. type="text"
  14. value={value}
  15. onChange={onChange}
  16. # leanpub-start-insert
  17. ref={(node) => input = node}
  18. # leanpub-end-insert
  19. />
  20. <button type="submit">
  21. {children}
  22. </button>
  23. </form>
  24. );
  25. }

Now you would be able to access the input DOM element. In the example of the focus use case it wouldn’t help you, because you have no lifecycle method in a functional stateless component to trigger the focus. But in the future you might come across other use cases where it can make sense to use a functional stateless component with the ref attribute.

Exercises

Loading …

Now let’s get back to the application. You might want to show a loading indicator when you submit a search request to the Hacker News API. The request is asynchronous and you should show your user some feedback that something is about to happen. Let’s define a reusable Loading component in your src/App.js file.

{title=”src/App.js”,lang=javascript}

  1. const Loading = () =>
  2. <div>Loading ...</div>

Now you will need a property to store the loading state. Based on the loading state you can decide to show the Loading component later on.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. results: null,
  6. searchKey: '',
  7. searchTerm: DEFAULT_QUERY,
  8. error: null,
  9. # leanpub-start-insert
  10. isLoading: false,
  11. # leanpub-end-insert
  12. };
  13. ...
  14. }
  15. ...
  16. }

The initial value of that isLoading property is false. You don’t load anything before the App component is mounted.

When you make the request, you set a loading state to true. Eventually the request will succeed and you can set the loading state to false.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. ...
  3. setSearchTopStories(result) {
  4. ...
  5. this.setState({
  6. results: {
  7. ...results,
  8. [searchKey]: { hits: updatedHits, page }
  9. },
  10. # leanpub-start-insert
  11. isLoading: false
  12. # leanpub-end-insert
  13. });
  14. }
  15. fetchSearchTopStories(searchTerm, page = 0) {
  16. # leanpub-start-insert
  17. this.setState({ isLoading: true });
  18. # leanpub-end-insert
  19. fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}&${PARAM_HPP}${DEFAULT_HPP}`)
  20. .then(response => response.json())
  21. .then(result => this.setSearchTopStories(result))
  22. .catch(e => this.setState({ error: e }));
  23. }
  24. ...
  25. }

In the last step, you will use the Loading component in your App. A conditional rendering based on the loading state will decide whether you show a Loading component or the Button component. The latter one is your button to fetch more data.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. ...
  3. render() {
  4. const {
  5. searchTerm,
  6. results,
  7. searchKey,
  8. error,
  9. # leanpub-start-insert
  10. isLoading
  11. # leanpub-end-insert
  12. } = this.state;
  13. ...
  14. return (
  15. <div className="page">
  16. ...
  17. <div className="interactions">
  18. # leanpub-start-insert
  19. { isLoading
  20. ? <Loading />
  21. : <Button
  22. onClick={() => this.fetchSearchTopStories(searchKey, page + 1)}>
  23. More
  24. </Button>
  25. }
  26. # leanpub-end-insert
  27. </div>
  28. </div>
  29. );
  30. }
  31. }

Initially the Loading component will show up when you start your application, because you make a request on componentDidMount(). There is no Table component, because the list is empty. When the response returns from the Hacker News API, the result is shown, the loading state is set to false and the Loading component disappears. Instead, the “More” button to fetch more data appears. Once you fetch more data, the button will disappear again and the Loading component will show up.

Exercises:

  • use a library such as Font Awesome to show a loading icon instead of the “Loading …” text

Higher Order Components

Higher order components (HOC) are an advanced concept in React. HOCs are an equivalent to higher order functions. They take any input - most of the time a component, but also optional arguments - and return a component as output. The returned component is an enhanced version of the input component and can be used in your JSX.

HOCs are used for different use cases. They can prepare properties, manage state or alter the representation of a component. One use case could be to use a HOC as a helper for a conditional rendering. Imagine you have a List component that renders a list of items or nothing, because the list is empty or null. The HOC could shield away that the list would render nothing when there is no list. On the other hand, the plain List component doesn’t need to bother anymore about an non existent list. It only cares about rendering the list.

Let’s do a simple HOC which takes a component as input and returns a component. You can place it in your src/App.js file.

{title=”src/App.js”,lang=javascript}

  1. function withFoo(Component) {
  2. return function(props) {
  3. return <Component { ...props } />;
  4. }
  5. }

One neat convention is to prefix the naming of a HOC with with. Since you are using JavaScript ES6, you can express the HOC more concisely with an ES6 arrow function.

{title=”src/App.js”,lang=javascript}

  1. const withFoo = (Component) => (props) =>
  2. <Component { ...props } />

In the example, the input component would stay the same as the output component. Nothing happens. It renders the same component instance and passes all of the props to the output component. But that’s useless. Let’s enhance the output component. The output component should show the Loading component, when the loading state is true, otherwise it should show the input component. A conditional rendering is a great use case for a HOC.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. const withLoading = (Component) => (props) =>
  3. props.isLoading
  4. ? <Loading />
  5. : <Component { ...props } />
  6. # leanpub-end-insert

Based on the loading property you can apply a conditional rendering. The function will return the Loading component or the input component.

In general it can be very efficient to spread an object, like the props object in the previous example, as input for a component. See the difference in the following code snippet.

{title=”Code Playground”,lang=”javascript”}

  1. // before you would have to destructure the props before passing them
  2. const { foo, bar } = props;
  3. <SomeComponent foo={foo} bar={bar} />
  4. // but you can use the object spread operator to pass all object properties
  5. <SomeComponent { ...props } />

There is one little thing that you should avoid. You pass all the props including the isLoading property, by spreading the object, into the input component. However, the input component may not care about the isLoading property. You can use the ES6 rest destructuring to avoid it.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. const withLoading = (Component) => ({ isLoading, ...rest }) =>
  3. isLoading
  4. ? <Loading />
  5. : <Component { ...rest } />
  6. # leanpub-end-insert

It takes one property out of the object, but keeps the remaining object. It works with multiple properties as well. You might have already read about it in the destructuring assignment.

Now you can use the HOC in your JSX. An use case in the application could be to show either the “More” button or the Loading component. The Loading component is already encapsulated in the HOC, but an input component is missing. In the use case of showing a Button component or a Loading component, the Button is the input component of the HOC. The enhanced output component is a ButtonWithLoading component.

{title=”src/App.js”,lang=javascript}

  1. const Button = ({ onClick, className = '', children }) =>
  2. <button
  3. onClick={onClick}
  4. className={className}
  5. type="button"
  6. >
  7. {children}
  8. </button>
  9. const Loading = () =>
  10. <div>Loading ...</div>
  11. const withLoading = (Component) => ({ isLoading, ...rest }) =>
  12. isLoading
  13. ? <Loading />
  14. : <Component { ...rest } />
  15. # leanpub-start-insert
  16. const ButtonWithLoading = withLoading(Button);
  17. # leanpub-end-insert

Everything is defined now. As a last step, you have to use the ButtonWithLoading component, which receives the loading state as an additional property. While the HOC consumes the loading property, all other props get passed to the Button component.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. ...
  3. render() {
  4. ...
  5. return (
  6. <div className="page">
  7. ...
  8. <div className="interactions">
  9. # leanpub-start-insert
  10. <ButtonWithLoading
  11. isLoading={isLoading}
  12. onClick={() => this.fetchSearchTopStories(searchKey, page + 1)}>
  13. More
  14. </ButtonWithLoading>
  15. # leanpub-end-insert
  16. </div>
  17. </div>
  18. );
  19. }
  20. }

When you run your tests again, you will notice that your snapshot test for the App component fails. The diff might look like the following on the command line:

{title=”Command Line”,lang=”text”}

  1. - <button
  2. - className=""
  3. - onClick={[Function]}
  4. - type="button"
  5. - >
  6. - More
  7. - </button>
  8. + <div>
  9. + Loading ...
  10. + </div>

You can either fix the component now, when you think there is something wrong about it, or can accept the new snapshot of it. Because you introduced the Loading component in this chapter, you can accept the altered snapshot test on the command line in the interactive test.

Higher order components are an advanced technique in React. They have multiple purposes like improved reusability of components, greater abstraction, composability of components and manipulations of props, state and view. Don’t worry if you don’t understand them immediately. It takes time to get used to them.

I encourage you to read the gentle introduction to higher order components. It gives you another approach to learn them, shows you an elegant way to use them a functional programming way and solves specifically the problem of conditional rendering with higher order components.

Exercises:

Advanced Sorting

You have already implemented a client- and server-side search interaction. Since you have a Table component, it would make sense to enhance the Table with advanced interactions. What about introducing a sort functionality for each column by using the column headers of the Table?

It would be possible to write your own sort function, but personally I prefer to use a utility library for such cases. Lodash is one of these utility libraries, but you can use whatever library suits you. Let’s install Lodash and use it for the sort functionality.

{title=”Command Line”,lang=”text”}

  1. npm install lodash

Now you can import the sort functionality of Lodash in your src/App.js file.

{title=”src/App.js”,lang=javascript}

  1. import React, { Component } from 'react';
  2. import fetch from 'isomorphic-fetch';
  3. # leanpub-start-insert
  4. import { sortBy } from 'lodash';
  5. # leanpub-end-insert
  6. import './App.css';

You have several columns in your Table. There are title, author, comments and points columns. You can define sort functions whereas each function takes a list and returns a list of items sorted by a specific property. Additionally, you will need one default sort function which doesn’t sort but only returns the unsorted list. That will be your initial state.

{title=”src/App.js”,lang=javascript}

  1. ...
  2. # leanpub-start-insert
  3. const SORTS = {
  4. NONE: list => list,
  5. TITLE: list => sortBy(list, 'title'),
  6. AUTHOR: list => sortBy(list, 'author'),
  7. COMMENTS: list => sortBy(list, 'num_comments').reverse(),
  8. POINTS: list => sortBy(list, 'points').reverse(),
  9. };
  10. # leanpub-end-insert
  11. class App extends Component {
  12. ...
  13. }
  14. ...

You can see that two of the sort functions return a reversed list. That’s because you want to see the items with the highest comments and points rather than to see the items with the lowest counts when you sort the list for the first time.

The SORTS object allows you to reference any sort function now.

Again your App component is responsible for storing the state of the sort. The initial state will be the initial default sort function, which doesn’t sort at all and returns the input list as output.

{title=”src/App.js”,lang=javascript}

  1. this.state = {
  2. results: null,
  3. searchKey: '',
  4. searchTerm: DEFAULT_QUERY,
  5. error: null,
  6. isLoading: false,
  7. # leanpub-start-insert
  8. sortKey: 'NONE',
  9. # leanpub-end-insert
  10. };

Once you choose a different sortKey, let’s say the AUTHOR key, you will sort the list with the appropriate sort function from the SORTS object.

Now you can define a new class method in your App component that simply sets a sortKey to your local component state. Afterward, the sortKey can be used to retrieve the sorting function to apply it on your list.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. constructor(props) {
  3. ...
  4. this.needsToSearchTopStories = this.needsToSearchTopStories.bind(this);
  5. this.setSearchTopStories = this.setSearchTopStories.bind(this);
  6. this.fetchSearchTopStories = this.fetchSearchTopStories.bind(this);
  7. this.onSearchSubmit = this.onSearchSubmit.bind(this);
  8. this.onSearchChange = this.onSearchChange.bind(this);
  9. this.onDismiss = this.onDismiss.bind(this);
  10. # leanpub-start-insert
  11. this.onSort = this.onSort.bind(this);
  12. # leanpub-end-insert
  13. }
  14. # leanpub-start-insert
  15. onSort(sortKey) {
  16. this.setState({ sortKey });
  17. }
  18. # leanpub-end-insert
  19. ...
  20. }

The next step is to pass the method and sortKey to your Table component.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. ...
  3. render() {
  4. const {
  5. searchTerm,
  6. results,
  7. searchKey,
  8. error,
  9. isLoading,
  10. # leanpub-start-insert
  11. sortKey
  12. # leanpub-end-insert
  13. } = this.state;
  14. ...
  15. return (
  16. <div className="page">
  17. ...
  18. <Table
  19. list={list}
  20. # leanpub-start-insert
  21. sortKey={sortKey}
  22. onSort={this.onSort}
  23. # leanpub-end-insert
  24. onDismiss={this.onDismiss}
  25. />
  26. ...
  27. </div>
  28. );
  29. }
  30. }

The Table component is responsible for sorting the list. It takes one of the SORT functions by sortKey and passes the list as input. Afterward it keeps mapping over the sorted list.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. const Table = ({
  3. list,
  4. sortKey,
  5. onSort,
  6. onDismiss
  7. }) =>
  8. # leanpub-end-insert
  9. <div className="table">
  10. # leanpub-start-insert
  11. {SORTS[sortKey](list).map(item =>
  12. # leanpub-end-insert
  13. <div key={item.objectID} className="table-row">
  14. ...
  15. </div>
  16. )}
  17. </div>

In theory the list would get sorted by one of the functions. But the default sort is set to NONE, so nothing is sorted yet. So far, no one executes the onSort() method to change the sortKey. Let’s extend the Table with a row of column headers that use Sort components in columns to sort each column.

{title=”src/App.js”,lang=javascript}

  1. const Table = ({
  2. list,
  3. sortKey,
  4. onSort,
  5. onDismiss
  6. }) =>
  7. <div className="table">
  8. # leanpub-start-insert
  9. <div className="table-header">
  10. <span style={{ width: '40%' }}>
  11. <Sort
  12. sortKey={'TITLE'}
  13. onSort={onSort}
  14. >
  15. Title
  16. </Sort>
  17. </span>
  18. <span style={{ width: '30%' }}>
  19. <Sort
  20. sortKey={'AUTHOR'}
  21. onSort={onSort}
  22. >
  23. Author
  24. </Sort>
  25. </span>
  26. <span style={{ width: '10%' }}>
  27. <Sort
  28. sortKey={'COMMENTS'}
  29. onSort={onSort}
  30. >
  31. Comments
  32. </Sort>
  33. </span>
  34. <span style={{ width: '10%' }}>
  35. <Sort
  36. sortKey={'POINTS'}
  37. onSort={onSort}
  38. >
  39. Points
  40. </Sort>
  41. </span>
  42. <span style={{ width: '10%' }}>
  43. Archive
  44. </span>
  45. </div>
  46. # leanpub-end-insert
  47. {SORTS[sortKey](list).map(item =>
  48. ...
  49. )}
  50. </div>

Each Sort component gets a specific sortKey and the general onSort() function. Internally it calls the method with the sortKey to set the specific key.

{title=”src/App.js”,lang=javascript}

  1. const Sort = ({ sortKey, onSort, children }) =>
  2. <Button onClick={() => onSort(sortKey)}>
  3. {children}
  4. </Button>

As you can see, the Sort component reuses your common Button component. On a button click each individual passed sortKey will get set by the onSort() method. Now you should be able to sort the list when you click on the column headers.

There is one minor improvement for an improved look. So far, the button in a column header looks a bit silly. Let’s give the button in the Sort component a proper className.

{title=”src/App.js”,lang=javascript}

  1. const Sort = ({ sortKey, onSort, children }) =>
  2. # leanpub-start-insert
  3. <Button
  4. onClick={() => onSort(sortKey)}
  5. className="button-inline"
  6. >
  7. # leanpub-end-insert
  8. {children}
  9. </Button>

It should look nice now. The next goal would be to implement a reverse sort as well. The list should get reverse sorted once you click a Sort component twice. First, you need to define the reverse state with a boolean. The sort can be either reversed or non reversed.

{title=”src/App.js”,lang=javascript}

  1. this.state = {
  2. results: null,
  3. searchKey: '',
  4. searchTerm: DEFAULT_QUERY,
  5. error: null,
  6. isLoading: false,
  7. sortKey: 'NONE',
  8. # leanpub-start-insert
  9. isSortReverse: false,
  10. # leanpub-end-insert
  11. };

Now in your sort method, you can evaluate if the list is reverse sorted. It is reverse if the sortKey in the state is the same as the incoming sortKey and the reverse state is not already set to true.

{title=”src/App.js”,lang=javascript}

  1. onSort(sortKey) {
  2. # leanpub-start-insert
  3. const isSortReverse = this.state.sortKey === sortKey && !this.state.isSortReverse;
  4. this.setState({ sortKey, isSortReverse });
  5. # leanpub-end-insert
  6. }

Again you can pass the reverse prop to your Table component.

{title=”src/App.js”,lang=javascript}

  1. class App extends Component {
  2. ...
  3. render() {
  4. const {
  5. searchTerm,
  6. results,
  7. searchKey,
  8. error,
  9. isLoading,
  10. sortKey,
  11. # leanpub-start-insert
  12. isSortReverse
  13. # leanpub-end-insert
  14. } = this.state;
  15. ...
  16. return (
  17. <div className="page">
  18. ...
  19. <Table
  20. list={list}
  21. sortKey={sortKey}
  22. # leanpub-start-insert
  23. isSortReverse={isSortReverse}
  24. # leanpub-end-insert
  25. onSort={this.onSort}
  26. onDismiss={this.onDismiss}
  27. />
  28. ...
  29. </div>
  30. );
  31. }
  32. }

The Table has to have an arrow function block body to compute the data now.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. const Table = ({
  3. list,
  4. sortKey,
  5. isSortReverse,
  6. onSort,
  7. onDismiss
  8. }) => {
  9. const sortedList = SORTS[sortKey](list);
  10. const reverseSortedList = isSortReverse
  11. ? sortedList.reverse()
  12. : sortedList;
  13. return(
  14. # leanpub-end-insert
  15. <div className="table">
  16. <div className="table-header">
  17. ...
  18. </div>
  19. # leanpub-start-insert
  20. {reverseSortedList.map(item =>
  21. # leanpub-end-insert
  22. ...
  23. )}
  24. </div>
  25. # leanpub-start-insert
  26. );
  27. }
  28. # leanpub-end-insert

The reverse sort should work now.

Last but not least, you have to deal with one open question for the sake of an improved user experience. Can a user distinguish which column is actively sorted? So far, it is not possible. Let’s give the user a visual feedback.

Each Sort component gets its specific sortKey already. It could be used to identify the activated sort. You can pass the sortKey from the internal component state as active sort key to your Sort component.

{title=”src/App.js”,lang=javascript}

  1. const Table = ({
  2. list,
  3. sortKey,
  4. isSortReverse,
  5. onSort,
  6. onDismiss
  7. }) => {
  8. const sortedList = SORTS[sortKey](list);
  9. const reverseSortedList = isSortReverse
  10. ? sortedList.reverse()
  11. : sortedList;
  12. return(
  13. <div className="table">
  14. <div className="table-header">
  15. <span style={{ width: '40%' }}>
  16. <Sort
  17. sortKey={'TITLE'}
  18. onSort={onSort}
  19. # leanpub-start-insert
  20. activeSortKey={sortKey}
  21. # leanpub-end-insert
  22. >
  23. Title
  24. </Sort>
  25. </span>
  26. <span style={{ width: '30%' }}>
  27. <Sort
  28. sortKey={'AUTHOR'}
  29. onSort={onSort}
  30. # leanpub-start-insert
  31. activeSortKey={sortKey}
  32. # leanpub-end-insert
  33. >
  34. Author
  35. </Sort>
  36. </span>
  37. <span style={{ width: '10%' }}>
  38. <Sort
  39. sortKey={'COMMENTS'}
  40. onSort={onSort}
  41. # leanpub-start-insert
  42. activeSortKey={sortKey}
  43. # leanpub-end-insert
  44. >
  45. Comments
  46. </Sort>
  47. </span>
  48. <span style={{ width: '10%' }}>
  49. <Sort
  50. sortKey={'POINTS'}
  51. onSort={onSort}
  52. # leanpub-start-insert
  53. activeSortKey={sortKey}
  54. # leanpub-end-insert
  55. >
  56. Points
  57. </Sort>
  58. </span>
  59. <span style={{ width: '10%' }}>
  60. Archive
  61. </span>
  62. </div>
  63. {reverseSortedList.map(item =>
  64. ...
  65. )}
  66. </div>
  67. );
  68. }

Now in your Sort component, you know based on the sortKey and activeSortKey whether the sort is active. Give your Sort component an extra className attribute, in case it is sorted, to give the user a visual feedback.

{title=”src/App.js”,lang=javascript}

  1. # leanpub-start-insert
  2. const Sort = ({
  3. sortKey,
  4. activeSortKey,
  5. onSort,
  6. children
  7. }) => {
  8. const sortClass = ['button-inline'];
  9. if (sortKey === activeSortKey) {
  10. sortClass.push('button-active');
  11. }
  12. return (
  13. <Button
  14. onClick={() => onSort(sortKey)}
  15. className={sortClass.join(' ')}
  16. >
  17. {children}
  18. </Button>
  19. );
  20. }
  21. # leanpub-end-insert

The way to define the sortClass is a bit clumsy, isn’t it? There is a neat little library to get rid of this. First you have to install it.

{title=”Command Line”,lang=”text”}

  1. npm install classnames

And second you have to import it on top of your src/App.js file.

{title=”src/App.js”,lang=javascript}

  1. import React, { Component } from 'react';
  2. import fetch from 'isomorphic-fetch';
  3. import { sortBy } from 'lodash';
  4. # leanpub-start-insert
  5. import classNames from 'classnames';
  6. # leanpub-end-insert
  7. import './App.css';

Now you can use it to define your component className with conditional classes.

{title=”src/App.js”,lang=javascript}

  1. const Sort = ({
  2. sortKey,
  3. activeSortKey,
  4. onSort,
  5. children
  6. }) => {
  7. # leanpub-start-insert
  8. const sortClass = classNames(
  9. 'button-inline',
  10. { 'button-active': sortKey === activeSortKey }
  11. );
  12. # leanpub-end-insert
  13. return (
  14. # leanpub-start-insert
  15. <Button
  16. onClick={() => onSort(sortKey)}
  17. className={sortClass}
  18. >
  19. # leanpub-end-insert
  20. {children}
  21. </Button>
  22. );
  23. }

Again, when you run your tests, you should see failing snapshot tests but also failing unit tests for the Table component. Since you changed again your component representations, you can accept the snapshot tests. But you have to fix the unit test. In your src/App.test.js file, you need to provide a sortKey and the isSortReverse boolean for the Table component.

{title=”src/App.test.js”,lang=javascript}

  1. ...
  2. describe('Table', () => {
  3. const props = {
  4. list: [
  5. { title: '1', author: '1', num_comments: 1, points: 2, objectID: 'y' },
  6. { title: '2', author: '2', num_comments: 1, points: 2, objectID: 'z' },
  7. ],
  8. # leanpub-start-insert
  9. sortKey: 'TITLE',
  10. isSortReverse: false,
  11. # leanpub-end-insert
  12. };
  13. ...
  14. });

Once again you might need to accept the failing snapshot tests for your Table component, because you provided extended props for the Table component.

Finally your advanced sort interaction is complete now.

Exercises:

  • use a library like Font Awesome to indicate the (reverse) sort
    • it could be an arrow up or arrow down icon next to each Sort header
  • read more about the classnames library

{pagebreak}

You have learned advanced component techniques in React! Let’s recap the last chapters:

  • React
    • the ref attribute to reference DOM nodes
    • higher order components are a common way to build advanced components
    • implementation of advanced interactions in React
    • conditional classNames with a neat helper library
  • ES6
    • rest destructuring to split up objects and arrays

You can find the source code in the official repository.