Version: 2.0.0-alpha.71 🚧

Docusaurus Client API

Docusaurus provides some APIs on the clients that can be helpful to you when building your site.

Components#

<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>

<Link/>#

This component enables linking to internal pages as well as a powerful performance feature called preloading. Preloading is used to prefetch resources so that the resources are fetched by the time the user navigates with this component. We use an IntersectionObserver to fetch a low-priority request when the <Link> is in the viewport and then use an onMouseOver event to trigger a high-priority request when it is likely that a user will navigate to the requested resource.

The component is a wrapper around react-router’s <Link> component that adds useful enhancements specific to Docusaurus. All props are passed through to react-router’s <Link> component.

import React from 'react';
import Link from '@docusaurus/Link';
const Page = () => (
<div>
<p>
Check out my <Link to="/blog">blog</Link>!
</p>
<p>
{/* Note that external links still use `a` tags, but automatically opens in new tab. */}
Follow me on <a href="https://twitter.com/docusaurus">Twitter</a>!
</p>
</div>
);

to: string#

The target location to navigate to. Example: /docs/introduction.

<Link to="/courses" />

<Redirect/>#

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do. You can refer to React Router's Redirect documentation for more info on available props.

Example usage:

import React from 'react';
import {Redirect} from '@docusaurus/router';
const Home = () => {
return <Redirect to="/docs/test" />;
};
note

@docusaurus/router implements React Router and supports its features.

<BrowserOnly/>#

The <BrowserOnly> component accepts a children prop, a render function which will not be executed during the pre-rendering phase of the build process. This is useful for hiding code that is only meant to run in the browsers (e.g. where the window/document objects are being accessed). To improve SEO, you can also provide fallback content using the fallback prop, which will be prerendered until in the build process and replaced with the client-side only contents when viewed in the browser.

import BrowserOnly from '@docusaurus/BrowserOnly';
const MyComponent = () => {
return (
<BrowserOnly
fallback={<div>The fallback content to display on prerendering</div>}>
{() => {
// Something that should be excluded during build process prerendering.
}}
</BrowserOnly>
);
};

<Translate/>#

When localizing your site, the <Translate/> component will allow providing translation support to React components, such as your homepage.

The translation strings will be extracted from your code with the docusaurus write-translations CLI and create a code.json translation file in website/i18n/<locale>.

note

The <Translate/> props must be hardcoded strings.

It is not possible to use variables, or the extraction wouldn't work.

Props#

  • children: untranslated string in the default site locale`
  • id: optional value to use as key in JSON translation files
  • description: optional text to help the translator

Example#

src/index.js
import React from 'react';
import Layout from '@theme/Layout';
import Translate from '@docusaurus/Translate';
export default function Home() {
return (
<Layout>
<h1>
<Translate
id="homepage.title"
description="The homepage welcome message">
Welcome to my website
</Translate>
</h1>
<main>
<Translate>My website content</Translate>
</main>
</Layout>
);
}

Hooks#

useDocusaurusContext#

React hook to access Docusaurus Context. Context contains siteConfig object from docusaurus.config.js, and some additional site metadata.

type DocusaurusPluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};
interface DocusaurusSiteMetadata {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, DocusaurusPluginVersionInformation>;
}
interface DocusaurusContext {
siteConfig: DocusaurusConfig;
siteMetadata: DocusaurusSiteMetadata;
}

Usage example:

import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const MyComponent = () => {
const {siteConfig, siteMetadata} = useDocusaurusContext();
return (
<div>
<h1>{siteConfig.title}</h1>
<div>{siteMetadata.siteVersion}</div>
<div>{siteMetadata.docusaurusVersion}</div>
</div>
);
};

useBaseUrl#

React hook to automatically prepend baseUrl to a string automatically. This is particularly useful if you don't want to hardcode your config's baseUrl. We highly recommend you to use this.

type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};

Example usage:

import React from 'react';
import Link from '@docusaurus/Link';
import useBaseUrl from '@docusaurus/useBaseUrl';
const Help = () => {
return (
<div className="col">
<h2>Browse the docs</h2>
<p>
Learn more about Docusaurus using the{' '}
<Link to={useBaseUrl('docs/introduction')}>official documentation</Link>
</p>
</div>
);
};

useBaseUrlUtils#

Sometimes useBaseUrl is not good enough. This hook return additional utils related to your site's base url.

  • withBaseUrl: useful if you need to add base urls to multiple urls at once
import React from 'react';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
const Component = () => {
const urls = ['/a', '/b'];
const {withBaseUrl} = useBaseUrlUtils();
const urlsWithBaseUrl = urls.map(withBaseUrl);
return <div className="col">{/* ... */}</div>;
};

useGlobalData#

React hook to access Docusaurus global data created by all the plugins.

Global data is namespaced by plugin name, and plugin id.

info

Plugin id is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data.

type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;

Usage example:

import React from 'react';
import useGlobalData from '@docusaurus/useGlobalData';
const MyComponent = () => {
const globalData = useGlobalData();
const myPluginData = globalData['my-plugin']['default'];
return <div>{myPluginData.someAttribute}</div>;
};
tip

Inspect your site's global data at ./docusaurus/globalData.json

usePluginData#

Access global data created by a specific plugin instance.

This is the most convenient hook to access plugin global data, and should be used most of the time.

pluginId is optional if you don't use multi-instance plugins.

usePluginData(pluginName: string, pluginId?: string)

Usage example:

import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};

useAllPluginInstancesData#

Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by plugin id.

useAllPluginInstancesData(pluginName: string)

Usage example:

import React from 'react';
import {useAllPluginInstancesData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const allPluginInstancesData = useAllPluginInstancesData('my-plugin');
const myPluginData = allPluginInstancesData['default'];
return <div>{myPluginData.someAttribute}</div>;
};

Functions#

translate#

The imperative counterpart of the <Translate> component.

tip

Use the imperative API for the rare cases when a component cannot be used, such as:

  • the placeholder props of form input
  • the page title metadata
src/index.js
import React from 'react';
import Layout from '@theme/Layout';
import {translate} from '@docusaurus/Translate';
export default function Home() {
return (
<Layout
title={translate({message: 'My page meta title'})}
>
<input
type="text"
placeholder={
translate({
message: 'Some input placeholder',
// Optional
id: 'homepage.input.placeholder',
description: 'The homepage input placeholder',
})
}
/>
</Layout>
);
}

Modules#

ExecutionEnvironment#

A module which exposes a few boolean variables to check the current rendering environment. Useful if you want to only run certain code on client/server or need to write server-side rendering compatible code.

import React from 'react';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
const MyPage = () => {
const location = ExecutionEnvironment.canUseDOM ? window.location.href : null;
return <div>{location}</div>;
};
FieldDescription
ExecutionEnvironment.canUseDOMtrue if on client, false if prerendering.
ExecutionEnvironment.canUseEventListenerstrue if on client and has window.addEventListener.
ExecutionEnvironment.canUseIntersectionObservertrue if on client and has IntersectionObserver.
ExecutionEnvironment.canUseViewporttrue if on client and has window.screen.

constants#

A module exposing useful constants to client-side theme code.

import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
Named exportValue
DEFAULT_PLUGIN_IDdefault
Last updated on by slorber