Docusaurus Client API
Docusaurus provides some APIs on the clients that can be helpful to you when building your site.
Components
<ErrorBoundary />
This component creates a React error boundary.
Use it to wrap components that might throw, and display a fallback when that happens instead of crashing the whole app.
import React from 'react';
import ErrorBoundary from '@docusaurus/ErrorBoundary';
const SafeComponent = () => (
<ErrorBoundary
fallback={({error, tryAgain}) => (
<div>
<p>This component crashed because of error: {error.message}.</p>
<button onClick={tryAgain}>Try Again!</button>
</div>
)}>
<SomeDangerousComponentThatMayThrow />
</ErrorBoundary>
);
To see it in action, click here:
Docusaurus uses this component to catch errors within the theme's layout, and also within the entire app.
This component doesn't catch build-time errors and only protects against client-side render errors that can happen when using stateful React components.
Props
fallback
: an optional render callback returning a JSX element. It will receive an object with 2 attributes:error
, the error that was caught, andtryAgain
, a function (() => void
) callback to reset the error in the component and try rendering it again. If not present,@theme/Error
will be rendered instead.@theme/Error
is used for the error boundaries wrapping the site, above the layout.
The fallback
prop is a callback, and not a React functional component. You can't use React hooks inside this callback.
<Head/>
This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags and is beginner-friendly. It is a wrapper around React Helmet.
Usage Example:
import React from 'react';
import Head from '@docusaurus/Head';
const MySEO = () => (
<Head>
<meta property="og:description" content="My custom description" />
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" />
</Head>
);
Nested or latter components will override duplicate usages:
<Parent>
<Head>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Head>
<Child>
<Head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Head>
</Child>
</Parent>
Outputs:
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>