Categories
React Answers

How to Use React Error Boundaries to Handle Errors Gracefully?

We can use React error boundaries to handle errors gracefully in a React app.

In this article, we’ll look at how to use React error boundaries to handle errors gracefully in a React app.

Use React 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.

Conclusion

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.

Categories
React Answers

How to Set Focus On Input After Render in a React Component?

Sometimes, we want to set focus on an input element in a React component after rendering it.

In this article, we’ll look at how to set focus on an input element in a React component after rendering it.

Set Focus On Input After Render

To focus an input, we have to use the native DOM element focus method to do it. The method is available to input elements so we can call it.

We can use the useEffect hook to run something when the component renders. If we pass in an empty array as the 2nd argument, then the callback we pass into useEffect only runs when the component first loads.

For instance, we can write the following to do that:

import React from "react";

export default function App() {
  const input = React.createRef();
  React.useEffect(() => input.current.focus(), []);
  return (
    <div className="App">
      <input ref={input} />
    </div>
  );
}

In the code above, we have the useEffect hook and the input ref created with the createRef method, which passed into the ref prop of the input.

Then in the useEffect callback, we call input.current.focus() to call the focus method of our input element.

In the end, when we load the page, we’ll see that the input is focused when App loads as we desired.

Conclusion

To focus an input, we have to use the native DOM element focus method to do it. The method is available to input elements so we can call it.

We can use the useEffect hook to run something when the component renders. If we pass in an empty array as the 2nd argument, then the callback we pass into useEffect only runs when the component first loads.

Categories
React Answers

How to Set React Component Default Prop Values?

Sometimes, we want to set default values for React component props.

In this article, we’ll look at how to set default values for React component props.

Set React Component Default Prop Values

We can add default props to make sure we always have some values set for our props.

To set default props, we use the defaultProps property to set the default values of each prop.

For instance, we can write the following code to set default props for the Person component that we have above:

import React from "react";
const persons = [
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "Alex", lastName: "Jones" },
  { firstName: "May", lastName: "Wong" },
  {}
];
const Person = ({ firstName, lastName }) => (
  <div>
    {firstName} {lastName}
  </div>
);
Person.defaultProps = {
  firstName: "No",
  lastName: "Name"
};

export default function App() {
  return (
    <div>
      {persons.map((p, i) => (
        <Person {...p} key={i} />
      ))}
    </div>
  );
}

In the code above, we added:

Person.defaultProps = {
  firstName: "No",
  lastName: "Name"
};

to set the default values of the firstName and lastName props.

Then we’ll get the following displayed on the screen:

Jane Smith
Alex Jones
May Wong
No Name

Since we have an empty object in the persons array as the last entry. Therefore, the default values are rendered in place of whatever is passed in.

Conclusion

We can add default props to make sure we always have some values set for our props.

To set default props, we use the defaultProps property to set the default values of each prop.

Categories
React Answers

How to Render Lists in React Components?

Oftentimes, we want to render lists in our React app.

In this article, we’ll look at how to render lists in our React app.

Rendering Lists in React Components

We can render lists by mapping our data to the component that we use to render the list item.

To do the mapping, we use the array’s map instance method. We can do that as follows:

import React from "react";

const persons = [
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "Alex", lastName: "Jones" },
  { firstName: "May", lastName: "Wong" }
];

const Person = ({ firstName, lastName }) => (
  <div>
    {firstName} {lastName}
  </div>
);

export default function App() {
  return (
    <div>
      {persons.map((p, i) => (
        <Person {...p} key={i} />
      ))}
    </div>
  );
}

In the code above, we have the Persons array, which we call map on in App . In the map method, we pass in a callback to return the Person component with all the properties of each persons entry passed in as props.

We need the key prop so that React can identify them properly. Ideally, it’s a unique ID, but the array index can also be the value of the key prop.

Then in Person , we have the props in the parameters and we decompose the prop properties in variables with the destructuring syntax.

Therefore <Person {...p} /> is the same as:

<Person firstName={p.firstName} lastName={p.lastName} key={i} />

It’s a lot shorter if our prop name is the same as our object’s property names.

In the end, we see:

Jane Smith
Alex Jones
May Wong

displayed on the screen.

Conclusion

We can render lists by mapping our data to the component that we use to render the list item.

Categories
React Answers

How to Conditionally Display Items in a React Component

Oftentimes, we want to conditionally display items in a React component.

In this article, we’ll look at how to conditionally display items in a React component.

Conditionally Displaying Items in a React Component

We can conditionally display items in a React component in various ways.

One way is to use a ternary expression.

For instance, we can write:

render() {
  return (
    this.props.showMe ? <button type="submit">show me</button> : null
  );
}

The first item is shown if showMe is true and null is rendered otherwise.

We can also use the && operator.

For instance, we can write;

`{`showMe `&&` <button type="submit">show me</button>`}`

Is showMe is true then the button is rendered since the expression will be evaluated.

Conclusion

We can conditionally display items in a React component in various ways.