React Tips and Tricks — Fragments and Error Handling
Tags: react, webdev, programming, javascript
Published: 2021-01-23 19:54:23

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps. In this article, we’ll look at some tips and tricks to make building apps with React easier.

### React Fragments

We can’t have multiple root nodes in a React component. However, we can have a single root node that doesn’t render any component by using a React fragment as the root node.

We can reference a React fragment with the `React.Fragement` component or an empty tag.

For instance, we can write the following:

```
import React from "react";
`
export default function App() {
  return (
    <React.Fragment>
      <p>foo</p>
      <p>bar</p>
    </React.Fragment>
  );
}
```

or:

```
import React from "react";
`
export default function App() {
  return (
    <>
      <p>foo</p>
      <p>bar</p>
    </>
  );
}
```

`<React.Fragment>` is the same as `<>` .

### Use Error Boundaries to Handle Errors Gracefully

Error boundaries are components that are displayed when there’re errors. They have special hooks like `componentDidCatch` to let us retrieve error details and does actions on error accordingly.

We wrap error boundary components around components that may throw errors for them to work.

Error boundary components are always class-based components. There’s no function component equivalent for this.

For instance, we can define an error boundary component and use it as follows:

```
import React from "react";
`
function Foo() {
  throw new Error("error");
  return <div>foo</div>;
}
`
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {
      return <h1>Error occurred.</h1>;
    }
    return this.props.children;
  }
}
`
export default function App() {
  return (
    <ErrorBoundary>
      <Foo />
    </ErrorBoundary>
  );
}
```

In the code above, we defined the `ErrorBoundary` component, which has the `componentDidCatch` hook, which takes the `error` parameter with the error that’s raised, and `info` object with the error information.

Then we call `setState` to `hasError` to `true` so that we render an error message. We return `this.props.children` when there’re no errors so that we display the components that we put inside the `ErrorBoundary` component.

Therefore, when we have `Foo` , where we threw an error, then we display the ‘Error occurred’ message since `Foo` throws an error before rendering anything.

### Higher-Order Components

Higher-order components are components that render other components. It’s useful because it can be used to produce components that are modified by the higher-order component.

For instance, we can create a `colorizeElement` higher-order component to apply the color prop to a component with the value `blue` as the default. If the `color` prop is set, then it’ll override the value of the color prop that we pass inside.

We can create and use it as follows:

```
import React from "react";
`
const colorizeElement = Element => props => <Element color="blue" {...props} />;
`
const Foo = ({ color }) => {
  return <p style={{ color }}>foo</p>;
};
`
const ColoredFoo = colorizeElement(Foo);
`
export default function App() {
  return (
    <>
      <ColoredFoo color="red" />
      <ColoredFoo />
    </>
  );
}
```

In the code above, we have the `ColoredFoo` component that we created from the `colorizeElement` higher-order component. In the component, we pass in the `Element` , which is a React component, which returns a new function with `props` as a parameter and returns the `Element` with the `color` prop set as `'blue'` and also pass in other props that are passed in.

Then in `App` , we have the `ColoredFoo` components, one with color prop set and the other one without. Then the first one is red and the second is blue.

### React DevTools

React dev tools is an extension for Chrome and Firefox and it’s maintained by the React core team. It lets us inspect the values of props and states that are inside components.

We’ll run into bugs and issues that are hard to solve eventually, so it’s a handy tool for debugging.

### Conclusion

Error boundaries and higher-order components are great for displaying errors and modifying components respectively.

Fragments are great for rendering multiple items within one single root node. It doesn’t render any HTML element itself.

React dev tools is a great extension for debugging.