Ir para o conteúdo principal
Version: Canary 🚧

Client API do Docusaurus

O Docusaurus oferece algumas APIs nos clientes que podem ser úteis na construção do seu site.

Componentes

<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>
);
tip

To see it in action, click here:

info

Docusaurus uses this component to catch errors within the theme's layout, and also within the entire app.

note

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, and tryAgain, 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.
warning

The fallback prop is a callback, and not a React functional component. You can't use React hooks inside this callback.

Este componente React reutilizável irá gerenciar todas as suas alterações na cabeça do documento. Ele leva tags HTML simples e produz tags HTML simples e é amigável para iniciantes. É um wrapper em torno de React Helmet.

Exemplo de uso:

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

Os componentes aninhados ou posteriores substituirão os usos duplicados:

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

Resultados:

<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>

Este componente permite vincular a páginas internas, bem como um poderoso recurso de desempenho chamado pré-carregamento. O pré-carregamento é usado para pré-carregar os recursos para que eles sejam buscados quando o usuário navegar com este componente. Usamos um IntersectionObserver para obter uma solicitação de baixa prioridade quando <Link> estiver na janela de visualização e usar um evento onMouseOver para disparar uma solicitação de alta prioridade quando é provável que um usuário navegue até o recurso solicitado.

O componente é um componente wrapper em torno do componente <Link> do react-router que adiciona melhorias úteis específicas ao Docusaurus. Todas as propriedades são passadas para o componente <Link> de react-router.

Links externos também funcionam e automaticamente têm essas props: target="_blank" rel="noreferrer noopener".

import React from 'react';
import Link from '@docusaurus/Link';

const Page = () => (
<div>
<p>
Check out my <Link to="/blog">blog</Link>!
</p>
<p>
Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>!
</p>
</div>
);

to: string

O local de destino navegar. Exemplo: /docs/introduction.

<Link to="/courses" />
tip

Prefer this component to vanilla <a> tags because Docusaurus does a lot of optimizations (e.g. broken path detection, prefetching, applying base URL...) if you use <Link>.

<Redirect/>

Renderizar um <Redirect> navegará para um novo local. The new location will override the current location in the history stack like server-side redirects (HTTP 3xx) do. Você pode consultar Documentação de Redirecionamento do React Router para mais informações sobre as propriedades disponíveis.

Example usage:

import React from 'react';
import {Redirect} from '@docusaurus/router';

const Home = () => {
return <Redirect to="/docs/test" />;
};
note

@docusaurus/router implementa React Router e suporta suas funcionalidades.

<BrowserOnly/>

The <BrowserOnly> component permits to render React components only in the browser after the React app has hydrated.

tip

Use it for integrating with code that can't run in Node.js, because the window or document objects are being accessed.

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

import BrowserOnly from '@docusaurus/BrowserOnly';

const MyComponent = () => {
return (
<BrowserOnly>
{() => <span>page url = {window.location.href}</span>}
</BrowserOnly>
);
};

Example with a library

import BrowserOnly from '@docusaurus/BrowserOnly';

const MyComponent = (props) => {
return (
<BrowserOnly fallback={<div>Loading...</div>}>
{() => {
const LibComponent = require('some-lib').LibComponent;
return <LibComponent {...props} />;
}}
</BrowserOnly>
);
};

<Interpolate/>

Um componente simples de interpolação para o texto contendo espaços reservados dinâmicos.

Os espaços reservados serão substituídos pelos valores dinâmicos fornecidos e pelos elementos JSX de sua escolha (strings, links, styled elements...).

Props

  • children: texto contendo espaços reservados interpolação como {placeholderName}
  • values: objeto contendo valores de espaço reservado interpolado
import React from 'react';
import Link from '@docusaurus/Link';
import Interpolate from '@docusaurus/Interpolate';

export default function VisitMyWebsiteMessage() {
return (
<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>
);
}

<Translate/>

When localizing your site, the <Translate/> component will allow providing translation support to React components, such as your homepage. O componente <Translate> suporta interpolação.

The translation strings will statically extracted from your code with the docusaurus write-translations CLI and a code.json translation file will be created in website/i18n/[locale].

note

As propriedades <Translate/> devem ser strings codificadas.

Apart from the values prop used for interpolation, it is not possible to use variables, or the static extraction wouldn't work.

Props

  • children: string não traduzida na localidade padrão do site (pode conter espaços reservados de interpolação)
  • id: optional value to be used as the key in JSON translation files
  • description: texto opcional para ajudar o tradutor
  • values: objeto opcional contendo valores de espaço reservado de interpolação

Exemplo

src/pages/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 values={{firstName: 'Sébastien'}}>
{'Welcome, {firstName}! How are you?'}
</Translate>
</main>
</Layout>
);
}
note

You can even omit the children prop and specify a translation string in your code.json file manually after running the docusaurus write-translations CLI command.

<Translate id="homepage.title" />
info

The <Translate> component supports interpolation. You can also implement string pluralization through some custom code and the translate imperative API.

Ganchos

useDocusaurusContext

React hook para acessar o Contexto do Docusaurus. The context contains the siteConfig object from docusaurus.config.js and some additional site metadata.

type PluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};

type SiteMetadata = {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, PluginVersionInformation>;
};

type I18nLocaleConfig = {
label: string;
direction: string;
};

type I18n = {
defaultLocale: string;
locales: [string, ...string[]];
currentLocale: string;
localeConfigs: Record<string, I18nLocaleConfig>;
};

type DocusaurusContext = {
siteConfig: DocusaurusConfig;
siteMetadata: SiteMetadata;
globalData: Record<string, unknown>;
i18n: I18n;
codeTranslations: Record<string, string>;
};

Exemplo de uso:

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>
);
};
note

The siteConfig object only contains serializable values (values that are preserved after JSON.stringify()). Functions, regexes, etc. would be lost on the client side.

useIsBrowser

Returns true when the React app has successfully hydrated in the browser.

warning

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.

Exemplo de uso:

import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';

const MyComponent = () => {
const isBrowser = useIsBrowser();
return <div>{isBrowser ? 'Client' : 'Server'}</div>;
};

useBaseUrl

React hook para preceder seu site baseUrl para uma string.

warning

Não use para links regulares!

O prefixo /baseUrl/ é adicionado automaticamente a todos os caminhos absolutos por padrão:

  • Markdown: [link](/my/path) vinculará ao /baseUrl/my/path
  • React: <Link to="/my/path/">link</Link> irá vincular para /baseUrl/my/path

Opções

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

Example usage:

import React from 'react';
import useBaseUrl from '@docusaurus/useBaseUrl';

const SomeImage = () => {
const imgSrc = useBaseUrl('/img/myImage.png');
return <img src={imgSrc} />;
};
tip

Na maioria dos casos, você não precisa de useBaseUrl.

Prefira uma chamada require() para assets:

<img src={require('@site/static/img/myImage.png').default} />

useBaseUrlUtils

Às vezes useBaseUrl não é bom o suficiente. 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>{/* ... */}</div>;
};

useGlobalData

React hook para acessar os dados globais do Docusaurus criados por todos os plugins.

Global data is namespaced by plugin name then by plugin ID.

info

Plugin ID is only useful when a plugin is used multiple times on the same site. Cada instância do plugin é capaz de criar seus próprios dados globais.

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

Exemplo de uso:

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

Acesse dados globais criados por uma instância específica do plugin.

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

pluginId é opcional se você não usa plugins de múltiplas instâncias.

function usePluginData(
pluginName: string,
pluginId?: string,
options?: {failfast?: boolean},
);

Exemplo de uso:

import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';

const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};

useAllPluginInstancesData

Acesso a dados globais criados por um plugin específico. Dado o nome do plugin, ele retorna os dados de todas as instâncias de plugins desse nome, pelo id do plugin.

function useAllPluginInstancesData(
pluginName: string,
options?: {failfast?: boolean},
);

Exemplo de uso:

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

React hook to access the Docusaurus broken link checker APIs, exposing a way for a Docusaurus pages to report and collect their links and anchors.

warning

This is an advanced API that most Docusaurus users don't need to use directly.

It is already built-in in existing high-level components:

  • the <Link> component will collect links for you
  • the @theme/Heading (used for Markdown headings) will collect anchors

Use useBrokenLinks() if you implement your own <Heading> or <Link> component.

Exemplo de uso:

MyHeading.js
import useBrokenLinks from '@docusaurus/useBrokenLinks';

export default function MyHeading(props) {
useBrokenLinks().collectAnchor(props.id);
return <h2 {...props} />;
}
MyLink.js
import useBrokenLinks from '@docusaurus/useBrokenLinks';

export default function MyLink(props) {
useBrokenLinks().collectLink(props.href);
return <a {...props} />;
}

Funções

interpolação

A contrapartida obrigatória do componente <Interpolate>.

Assinatura

// Simple string interpolation
function interpolate(text: string, values: Record<string, string>): string;

// JSX interpolation
function interpolate(
text: string,
values: Record<string, ReactNode>,
): ReactNode;

Exemplo

import {interpolate} from '@docusaurus/Interpolate';

const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});

traduzir

A contraparte imperativa do componente <Translate>. Também suporta interpolação de placeholders.

tip

Use a API imperativa para os casos raros em que um componente não pode ser usado, como:

  • o metadado da página title
  • as propriedades placeholder de entradas de formulário
  • as propriedades aria-label para acessibilidade

Assinatura

function translate(
translation: {message: string; id?: string; description?: string},
values: Record<string, string>,
): string;

Exemplo

src/pages/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'})}>
<img
src={'https://docusaurus.io/logo.png'}
aria-label={
translate(
{
message: 'The logo of site {siteName}',
// Optional
id: 'homepage.logo.ariaLabel',
description: 'The home page logo aria label',
},
{siteName: 'Docusaurus'},
)
}
/>
</Layout>
);
}

Módulos

ExecutionEnvironment

A module that exposes a few boolean variables to check the current rendering environment.

warning

For React rendering logic, use useIsBrowser() or <BrowserOnly> instead.

Exemplo:

import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
CampoDescrição
ExecutionEnvironment.canUseDOMtrue if on client/browser, false on Node.js/prerendering.
ExecutionEnvironment.canUseEventListenerstrue se estiver no cliente e estiver window.addEventListener.
ExecutionEnvironment.canUseIntersectionObservertrue se estiver no cliente e tiver IntersectionObserver.
ExecutionEnvironment.canUseViewporttrue se estiver no cliente e tiver window.screen.

constantes

Um módulo que expõe constantes úteis para o código do tema do lado do cliente.

import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
Exportação nomeadaValor
DEFAULT_PLUGIN_IDdefault