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>
);
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/>
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>
<Link/>
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://x.com/docusaurus">X</Link>!
</p>
</div>
);
to
: string
O local de destino navegar. Exemplo: /docs/introduction
.
<Link to="/courses" />
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" />;
};
@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.
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.jsfallback
(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>
);
}