2019-04-28 23:20:24 -04:00
---
id: docusaurus-core
2019-10-29 23:19:30 -04:00
title: Docusaurus Client API
2019-11-25 13:31:57 -05:00
sidebar_label: Client API
2019-04-28 23:20:24 -04:00
---
2020-02-18 20:22:14 -05:00
Docusaurus provides some APIs on the clients that can be helpful to you when building your site.
2019-04-28 23:20:24 -04:00
2021-03-19 06:00:41 -04:00
## Components {#components}
2020-02-18 20:22:14 -05:00
2021-03-19 06:00:41 -04:00
### `<Head/>` {#head}
2019-04-28 23:20:24 -04:00
2019-10-25 12:25:43 -04:00
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 ](https://github.com/nfl/react-helmet ).
2019-07-08 02:14:49 -04:00
2019-10-25 12:25:43 -04:00
Usage Example:
2020-11-30 08:39:51 -05:00
```jsx {2,5,10}
2019-10-25 12:25:43 -04:00
import React from 'react';
import Head from '@docusaurus/Head';
const MySEO = () => (
2020-11-30 08:39:51 -05:00
< 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 >
2019-10-25 12:25:43 -04:00
);
```
Nested or latter components will override duplicate usages:
2019-10-29 02:59:24 -04:00
```jsx {2,5,8,11}
2019-10-25 12:25:43 -04:00
< 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 >
```
2020-11-30 08:39:51 -05:00
Outputs:
2019-10-25 12:25:43 -04:00
```html
< head >
< title > Nested Title< / title >
< meta name = "description" content = "Nested component" / >
< / head >
```
2021-03-19 06:00:41 -04:00
### `<Link/>` {#link}
2019-10-25 12:25:43 -04:00
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.
2020-04-12 01:34:50 -04:00
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.
2019-10-25 12:25:43 -04:00
2021-07-23 06:24:03 -04:00
External links also work, and automatically have these props: `target="_blank" rel="noopener noreferrer"` .
2019-10-29 02:59:24 -04:00
```jsx {2,7}
2019-10-25 12:25:43 -04:00
import React from 'react';
import Link from '@docusaurus/Link';
const Page = () => (
< div >
< p >
Check out my < Link to = "/blog" > blog< / Link > !
< / p >
< p >
2021-07-23 06:24:03 -04:00
Follow me on < Link to = "https://twitter.com/docusaurus" > Twitter< / Link > !
2019-10-25 12:25:43 -04:00
< / p >
< / div >
);
```
2021-03-19 06:00:41 -04:00
#### `to`: string {#to-string}
2019-10-25 12:25:43 -04:00
The target location to navigate to. Example: `/docs/introduction` .
```jsx
< Link to = "/courses" / >
```
2021-03-19 06:00:41 -04:00
### `<Redirect/>` {#redirect}
2020-02-18 20:22:14 -05:00
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 ](https://reacttraining.com/react-router/web/api/Redirect ) for more info on available props.
Example usage:
2019-10-25 12:25:43 -04:00
2020-02-18 20:22:14 -05:00
```jsx {2,5}
import React from 'react';
import {Redirect} from '@docusaurus/router';
2020-11-30 08:39:51 -05:00
const Home = () => {
2020-02-18 20:22:14 -05:00
return < Redirect to = "/docs/test" / > ;
2020-11-30 08:39:51 -05:00
};
2020-02-18 20:22:14 -05:00
```
2020-06-15 06:37:49 -04:00
:::note
`@docusaurus/router` implements [React Router ](https://reacttraining.com/react-router/web/guides/quick-start ) and supports its features.
:::
2021-03-19 06:00:41 -04:00
### `<BrowserOnly/>` {#browseronly}
2020-03-29 11:43:57 -04:00
2021-08-12 13:02:29 -04:00
The `<BrowserOnly>` component permits to render React components only in the browser, after the React app has hydrated.
2020-03-29 11:43:57 -04:00
2021-08-12 13:02:29 -04:00
:::tip
Use it for integrating with code that can't run in Node.js, because `window` or `document` objects are being accessed.
:::
#### Props {#browseronly-props}
- `children` : render function prop returning browser-only JSX. Will not be executed in Node.js
- `fallback` (optional): JSX to render on the server (Node.js) and until React hydration completes.
#### Example with code {#browseronly-example-code}
```jsx
// highlight-start
2020-03-29 11:43:57 -04:00
import BrowserOnly from '@docusaurus/BrowserOnly';
2021-08-12 13:02:29 -04:00
// highlight-end
2020-03-29 11:43:57 -04:00
2020-11-30 08:39:51 -05:00
const MyComponent = () => {
2020-04-02 05:07:50 -04:00
return (
2021-08-12 13:02:29 -04:00
// highlight-start
< BrowserOnly >
{() => {
< span > page url = {window.location.href}< / span > ;
}}
< / BrowserOnly >
// highlight-end
);
};
```
#### Example with a library {#browseronly-example-library}
```jsx
// highlight-start
import BrowserOnly from '@docusaurus/BrowserOnly';
// highlight-end
const MyComponent = (props) => {
return (
// highlight-start
< BrowserOnly fallback = {<div > Loading...< / div > }>
2020-04-02 05:07:50 -04:00
{() => {
2021-08-12 13:02:29 -04:00
const LibComponent = require('some-lib').LibComponent;
return < LibComponent { . . . props } / > ;
2020-04-02 05:07:50 -04:00
}}
< / BrowserOnly >
2021-08-12 13:02:29 -04:00
// highlight-end
2020-04-02 05:07:50 -04:00
);
2020-11-30 08:39:51 -05:00
};
2020-03-29 11:43:57 -04:00
```
2021-03-19 06:00:41 -04:00
### `<Interpolate/>` {#interpolate}
2021-02-26 07:19:51 -05:00
A simple interpolation component for text containing dynamic placeholders.
The placeholders will be replaced with the provided dynamic values and JSX elements of your choice (strings, links, styled elements...).
2021-08-12 13:02:29 -04:00
#### Props {#interpolate-props}
2021-02-26 07:19:51 -05:00
- `children` : text containing interpolation placeholders like `{placeholderName}`
- `values` : object containing interpolation placeholder values
```jsx
import React from 'react';
import Link from '@docusaurus/Link';
import Interpolate from '@docusaurus/Interpolate';
export default function VisitMyWebsiteMessage() {
return (
// highlight-start
< Interpolate
values={{
firstName: 'Sébastien',
website: (
< Link to = "https://docusaurus.io" className = "my-website-class" >
website
< / Link >
),
}}>
{'Hello, {firstName}! How are you? Take a look at my {website}'}
< / Interpolate >
// highlight-end
);
}
```
2021-03-19 06:00:41 -04:00
### `<Translate/>` {#translate}
2021-01-19 11:26:31 -05:00
2021-02-26 07:19:51 -05:00
When [localizing your site ](./i18n/i18n-introduction.md ), the `<Translate/>` component will allow providing **translation support to React components** , such as your homepage. The `<Translate>` component supports [interpolation ](#interpolate ).
2021-01-19 11:26:31 -05:00
2021-06-20 15:16:17 -04:00
The translation strings will be extracted from your code with the [`docusaurus write-translations` ](./cli.md#docusaurus-write-translations-sitedir ) CLI and create a `code.json` translation file in `website/i18n/<locale>` .
2021-01-19 11:26:31 -05:00
:::note
The `<Translate/>` props **must be hardcoded strings** .
2021-02-26 07:19:51 -05:00
Apart the `values` prop used for interpolation, it is **not possible to use variables** , or the static extraction wouldn't work.
2021-01-19 11:26:31 -05:00
:::
2021-08-12 13:02:29 -04:00
#### Props {#translate-props}
2021-01-19 11:26:31 -05:00
2021-02-26 07:19:51 -05:00
- `children` : untranslated string in the default site locale (can contain [interpolation placeholders ](#interpolate ))
2021-01-19 11:26:31 -05:00
- `id` : optional value to use as key in JSON translation files
- `description` : optional text to help the translator
2021-02-26 07:19:51 -05:00
- `values` : optional object containing interpolation placeholder values
2021-01-19 11:26:31 -05:00
2021-03-19 06:00:41 -04:00
#### Example {#example}
2021-01-19 11:26:31 -05:00
2021-04-05 12:56:14 -04:00
```jsx title="src/pages/index.js"
2021-01-19 11:26:31 -05:00
import React from 'react';
import Layout from '@theme/Layout';
// highlight-start
import Translate from '@docusaurus/Translate';
// highlight-end
export default function Home() {
return (
< Layout >
< h1 >
{/* highlight-start */}
< Translate
id="homepage.title"
description="The homepage welcome message">
Welcome to my website
< / Translate >
{/* highlight-end */}
< / h1 >
< main >
{/* highlight-start */}
2021-02-26 07:19:51 -05:00
< Translate values = {{firstName: ' Sébastien ' } } >
{'Welcome, {firstName}! How are you?'}
< / Translate >
2021-01-19 11:26:31 -05:00
{/* highlight-end */}
< / main >
< / Layout >
);
}
```
2021-03-19 06:00:41 -04:00
## Hooks {#hooks}
2020-02-18 20:22:14 -05:00
2021-03-19 06:00:41 -04:00
### `useDocusaurusContext` {#usedocusauruscontext}
2020-02-18 20:22:14 -05:00
2020-07-31 15:14:49 -04:00
React hook to access Docusaurus Context. Context contains `siteConfig` object from [docusaurus.config.js ](api/docusaurus.config.js.md ), and some additional site metadata.
2019-10-25 12:25:43 -04:00
```ts
2020-07-16 06:46:21 -04:00
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 > ;
}
2021-08-11 10:07:17 -04:00
interface I18nLocaleConfig {
label: string;
direction: string;
}
interface I18n {
defaultLocale: string;
locales: [string, ...string[]];
currentLocale: string;
localeConfigs: Record< string , I18nLocaleConfig > ;
}
2019-10-25 12:25:43 -04:00
interface DocusaurusContext {
2020-07-16 06:46:21 -04:00
siteConfig: DocusaurusConfig;
siteMetadata: DocusaurusSiteMetadata;
2021-08-11 10:07:17 -04:00
globalData: Record< string , unknown > ;
i18n: I18n;
codeTranslations: Record< string , string > ;
2019-10-25 12:25:43 -04:00
}
```
Usage example:
2020-11-30 08:39:51 -05:00
```jsx {5,8-10}
2019-10-25 12:25:43 -04:00
import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
2020-07-16 06:46:21 -04:00
const MyComponent = () => {
const {siteConfig, siteMetadata} = useDocusaurusContext();
return (
< div >
< h1 > {siteConfig.title}< / h1 >
< div > {siteMetadata.siteVersion}< / div >
< div > {siteMetadata.docusaurusVersion}< / div >
< / div >
);
2019-10-25 12:25:43 -04:00
};
```
2021-08-12 13:02:29 -04:00
### `useIsBrowser` {#useIsBrowser}
Returns `true` when the React app has successfully hydrated in the browser.
:::caution
Use this hook instead of `typeof windows !== 'undefined'` in React rendering logic.
The first client-side render output (in the browser) **must be exactly the same** as the server-side render output (Node.js).
Not following this rule can lead to unexpected hydration behaviors, as described in [The Perils of Rehydration ](https://www.joshwcomeau.com/react/the-perils-of-rehydration/ ).
:::
Usage example:
```jsx
import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
const MyComponent = () => {
// highlight-start
const isBrowser = useIsBrowser();
// highlight-end
return < div > {isBrowser ? 'Client' : 'Server'}< / div > ;
};
```
2021-03-19 06:00:41 -04:00
### `useBaseUrl` {#usebaseurl}
2019-10-25 12:25:43 -04:00
2021-01-29 13:10:38 -05:00
React hook to prepend your site `baseUrl` to a string.
:::caution
**Don't use it for regular links!**
The `/baseUrl/` prefix is automatically added to all **absolute paths** by default:
- Markdown: `[link](/my/path)` will link to `/baseUrl/my/path`
- React: `<Link to="/my/path/">link</Link>` will link to `/baseUrl/my/path`
:::
2021-03-19 06:00:41 -04:00
#### Options {#options}
2019-10-25 12:25:43 -04:00
2020-06-02 03:48:22 -04:00
```ts
type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};
```
2021-03-19 06:00:41 -04:00
#### Example usage: {#example-usage}
2019-10-25 12:25:43 -04:00
2021-01-29 13:10:38 -05:00
```jsx
2020-07-08 11:51:59 -04:00
import React from 'react';
2019-10-25 12:25:43 -04:00
import useBaseUrl from '@docusaurus/useBaseUrl';
2019-07-08 02:14:49 -04:00
2021-01-29 13:10:38 -05:00
const SomeImage = () => {
// highlight-start
const imgSrc = useBaseUrl('/img/myImage.png');
// highlight-end
return < img src = {imgSrc} / > ;
2020-11-30 08:39:51 -05:00
};
2019-10-25 12:25:43 -04:00
```
2019-10-29 23:19:30 -04:00
2021-01-29 13:10:38 -05:00
:::tip
In most cases, you don't need `useBaseUrl` .
Prefer a `require()` call for [assets ](./guides/markdown-features/markdown-features-assets.mdx ):
```jsx
< img src = {require('@site/static/img/myImage.png').default} / >
```
:::
2021-03-19 06:00:41 -04:00
### `useBaseUrlUtils` {#usebaseurlutils}
2020-07-08 11:51:59 -04:00
Sometimes `useBaseUrl` is not good enough. This hook return additional utils related to your site's base url.
2021-01-29 13:10:38 -05:00
- `withBaseUrl` : useful if you need to add base urls to multiple urls at once.
2020-07-08 11:51:59 -04:00
2021-01-29 13:10:38 -05:00
```jsx
2020-07-08 11:51:59 -04:00
import React from 'react';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
2020-11-30 08:39:51 -05:00
const Component = () => {
2020-07-08 11:51:59 -04:00
const urls = ['/a', '/b'];
2021-01-29 13:10:38 -05:00
// highlight-start
2020-07-08 11:51:59 -04:00
const {withBaseUrl} = useBaseUrlUtils();
const urlsWithBaseUrl = urls.map(withBaseUrl);
2021-01-29 13:10:38 -05:00
// highlight-end
return < div > {/* ... */}< / div > ;
2020-11-30 08:39:51 -05:00
};
2020-07-08 11:51:59 -04:00
```
2021-03-19 06:00:41 -04:00
### `useGlobalData` {#useglobaldata}
2020-07-21 05:16:08 -04:00
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.
:::
```ts
type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;
```
Usage example:
2020-11-30 08:39:51 -05:00
```jsx {2,5-7}
2020-07-21 05:16:08 -04:00
import React from 'react';
import useGlobalData from '@docusaurus/useGlobalData';
const MyComponent = () => {
2020-11-30 08:39:51 -05:00
const globalData = useGlobalData();
2020-07-21 05:16:08 -04:00
const myPluginData = globalData['my-plugin']['default'];
return < div > {myPluginData.someAttribute}< / div > ;
};
```
:::tip
Inspect your site's global data at `./docusaurus/globalData.json`
:::
2021-03-19 06:00:41 -04:00
### `usePluginData` {#useplugindata}
2020-07-21 05:16:08 -04:00
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.
2020-11-30 08:39:51 -05:00
```ts
usePluginData(pluginName: string, pluginId?: string)
```
2020-07-21 05:16:08 -04:00
Usage example:
2020-11-30 08:39:51 -05:00
```jsx {2,5-6}
2020-07-21 05:16:08 -04:00
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return < div > {myPluginData.someAttribute}< / div > ;
};
```
2021-03-19 06:00:41 -04:00
### `useAllPluginInstancesData` {#useallplugininstancesdata}
2020-07-21 05:16:08 -04:00
2020-10-07 06:39:47 -04:00
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.
2020-07-21 05:16:08 -04:00
2020-11-30 08:39:51 -05:00
```ts
useAllPluginInstancesData(pluginName: string)
```
2020-07-21 05:16:08 -04:00
Usage example:
2020-11-30 08:39:51 -05:00
```jsx {2,5-7}
2020-07-21 05:16:08 -04:00
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 > ;
};
```
2021-03-19 06:00:41 -04:00
## Functions {#functions}
2021-01-19 11:26:31 -05:00
2021-03-19 06:00:41 -04:00
### `interpolate` {#interpolate-1}
2021-02-26 07:19:51 -05:00
The imperative counterpart of the [`<Interpolate>` ](#interpolate ) component.
2021-03-19 06:00:41 -04:00
#### Signature {#signature}
2021-02-26 07:19:51 -05:00
```ts
// Simple string interpolation
function interpolate(text: string, values: Record< string , string > ): string;
// JSX interpolation
function interpolate(
text: string,
values: Record< string , ReactNode > ,
): ReactNode;
```
2021-03-19 06:00:41 -04:00
#### Example {#example-1}
2021-02-26 07:19:51 -05:00
```jsx
// highlight-start
import {interpolate} from '@docusaurus/Interpolate';
// highlight-end
const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});
```
2021-03-19 06:00:41 -04:00
### `translate` {#translate-1}
2021-01-19 11:26:31 -05:00
2021-02-26 07:19:51 -05:00
The imperative counterpart of the [`<Translate>` ](#translate ) component. Also supporting [placeholders interpolation ](#interpolate ).
2021-01-19 11:26:31 -05:00
:::tip
2021-02-26 07:19:51 -05:00
Use the imperative API for the **rare cases** where a **component cannot be used** , such as:
2021-01-19 11:26:31 -05:00
- the page `title` metadata
2021-02-26 07:19:51 -05:00
- the `placeholder` props of form inputs
- the `aria-label` props for accessibility
2021-01-19 11:26:31 -05:00
:::
2021-03-19 06:00:41 -04:00
#### Signature {#signature-1}
2021-02-26 07:19:51 -05:00
```ts
function translate(
translation: {message: string; id?: string; description?: string},
values: Record< string , string > ,
): string;
```
2021-03-19 06:00:41 -04:00
#### Example {#example-2}
2021-02-26 07:19:51 -05:00
2021-04-05 12:56:14 -04:00
```jsx title="src/pages/index.js"
2021-01-19 11:26:31 -05:00
import React from 'react';
import Layout from '@theme/Layout';
// highlight-start
import {translate} from '@docusaurus/Translate';
// highlight-end
export default function Home() {
return (
< Layout
// highlight-start
title={translate({message: 'My page meta title'})}
// highlight-end
>
2021-02-26 07:19:51 -05:00
< img
src={'https://docusaurus.io/logo.png'}
aria-label={
2021-01-19 11:26:31 -05:00
// highlight-start
2021-02-26 07:19:51 -05:00
translate(
{
message: 'The logo of site {siteName}',
// Optional
id: 'homepage.logo.ariaLabel',
description: 'The home page logo aria label',
},
{siteName: 'Docusaurus'},
)
2021-01-19 11:26:31 -05:00
// highlight-end
}
/>
< / Layout >
);
}
```
2021-03-19 06:00:41 -04:00
## Modules {#modules}
2019-10-29 23:19:30 -04:00
2021-03-19 06:00:41 -04:00
### `ExecutionEnvironment` {#executionenvironment}
2019-10-29 23:19:30 -04:00
2021-08-12 13:02:29 -04:00
A module which exposes a few boolean variables to check the current rendering environment.
2019-10-29 23:19:30 -04:00
2021-08-12 13:02:29 -04:00
:::caution
For React rendering logic, use [`useIsBrowser()` ](#useIsBrowser ) or [`<BrowserOnly>` ](#browseronly ) instead.
:::
Example:
```jsx
2020-02-18 20:22:14 -05:00
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
2019-10-29 23:19:30 -04:00
2021-08-12 13:02:29 -04:00
if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
2019-10-29 23:19:30 -04:00
```
2020-02-18 20:22:14 -05:00
| Field | Description |
| --- | --- |
2021-08-12 13:02:29 -04:00
| `ExecutionEnvironment.canUseDOM` | `true` if on client/browser, `false` on Node.js/prerendering. |
2020-02-18 20:22:14 -05:00
| `ExecutionEnvironment.canUseEventListeners` | `true` if on client and has `window.addEventListener` . |
| `ExecutionEnvironment.canUseIntersectionObserver` | `true` if on client and has `IntersectionObserver` . |
| `ExecutionEnvironment.canUseViewport` | `true` if on client and has `window.screen` . |
2020-10-12 12:56:24 -04:00
2021-03-19 06:00:41 -04:00
### `constants` {#constants}
2020-10-12 12:56:24 -04:00
A module exposing useful constants to client-side theme code.
```jsx
import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
```
| Named export | Value |
| ------------------- | --------- |
| `DEFAULT_PLUGIN_ID` | `default` |