12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
11 : 17 : 39 : 10
Join egghead, unlock knowledge.

Want more egghead? It's 58% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 40% Off
Become a member
to unlock all features

    Set an Error Component in React Universal when a Component Fails to Load

    Tim KindbergTim Kindberg

    You can set the error component that will show when a component has an error during async loading. You can force the error to show manually as well.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: I'm going to try to load a file that doesn't exist. We have two buttons, one that loads the Home file, which does exist. The other button tries to load broken.js, which is not going to exist.

    When I click the broken button, it's going to set the state to broken. It's going to pass that to the tab prop. When the tab prop comes in and sends it to the import function, it's going to look for broken.js, and it's going to get an error.

    By default, universal will show this error message. It's pretty helpful, especially since it specifies which module that it couldn't find. You can change the error component that is shown by specifying the error option. I've created this simple notFound component. I'm going to pass it to the error option. Now, when I refresh and click broken, here's a simple component that I made.

    There are two other props that the output component from calling universal can receive. One of them is the error prop. What it does is it takes a Boolean, either true of false. You can basically force the error to be on.

    This is in case you are having maybe another error that you know of, and you want to tell universal, "Hey, I know there's an error, so just show the error component that you're configured to show." If we save that and refresh, even if I click Home, which is a good file, we're still going to see this error show up.

    The other prop is onError. This is more of a listener. I'm going to console log out the error that I receive as the parameter to this function. When I click broken, I'm actually going to see the same error message that is shown with the default component. I see "Error cannot find module 'broken.'" Then I also get a bit of a stack trace.