Skip to content

ErrorBoundary ​

Keeps a render failure to the subtree it happened in. Without one, React unmounts the whole tree on an error.

tsx
import { ErrorBoundary } from '@adecore/ui';
tsx
import { useState } from 'react';
import { Button, ErrorBoundary } from '@adecore/ui';

function Chart({ broken }: { broken: boolean }) {
    if (broken) {
        throw new Error('Cannot read the series "memory" of an empty sample.');
    }

    return <div className="grid h-full place-items-center text-xs text-text-muted">The chart draws here.</div>;
}

export default function ErrorBoundaryDemo() {
    const [broken, setBroken] = useState(false);

    return (
        <div className="flex w-full max-w-md flex-col items-center gap-3">
            <div className="relative h-56 w-full overflow-hidden rounded-lg border border-border bg-surface">
                <ErrorBoundary label="This chart failed to render" resetKeys={[broken]}>
                    <Chart broken={broken} />
                </ErrorBoundary>
            </div>
            <Button variant="secondary" onClick={() => setBroken(!broken)}>
                {broken ? 'Fix the data' : 'Break the chart'}
            </Button>
        </div>
    );
}

In place of the subtree it shows the error's message, a try again button and a button that copies a report with both stacks. It also logs the failure to the console.

Trying again ​

resetKeys lists what the children draw from. When one changes while the boundary holds an error, it draws its children again. Try again resets it by hand.

Give every surface that draws data of its own a boundary. Give the outermost one reload, which adds a button that reloads the page.

Props ​

PropTypeDefault
labelstringRequired. The first line of the message, such as "This view failed to render".
childrenReactNodeRequired.
resetKeysResetKeysreadonly unknown[], compared with Object.is.
compactbooleanfalseFor a small surface: no icon and less space.
reloadbooleanfalse
classNamestring'absolute inset-0'The box of the message; by default it covers the positioned parent.

ErrorBoundaryProps and ResetKeys are exported types.

Licenses and third-party notices are listed in each package.