도큐사우루스 클라이언트 API
도큐사우루스는 사이트를 만들 때 도움이 될 만한 API를 클라이언트에서 사용할 수 있게 제공합니다.
Components
<ErrorBoundary />
This component creates a React error boundary.
이를 사용해 컴포넌트를 래핑하고 에러가 발생했을 때 전체 앱 오류로 처리하는 대신 대체할 수 있는 UI를 보여줄 수 있습니다.
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:
도큐사우루스는 해당 컴포넌트를 사용해 테마 레이아웃과 전체 앱에서 발생하는 오류를 처리할 수 있습니다.
해당 컴포넌트는 빌드 시 오류는 처리하지 않으며 안정된 리액트 컴포넌트 사용 시 발생할 수 있는 클라이언트 측 렌더링 오류에 대해서만 처리합니다.
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. 콜백 내에서 리액트 후크를 사용할 수 없습니다.
<Head/>
재사용할 수 있는 리액트 컴포넌트로 문서 헤더 영역의 수정을 관리할 수 있습니다. 일반적인 HTML 태그를 사용하며 실제 출력 결과도 일반적인 HTML 태그입니다. 초보자들에게 적합합니다. It is a wrapper around React Helmet.
아래와 같이 작성합니다.
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>
);
중첩되거나 나중에 정의된 컴포넌트는 이전 값을 덮어씁니다.
<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>
출력 결과는 아래와 같습니다.
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>
<Link/>
내부 페이지에 연결하거나 미리 콘텐츠를 불러와서(preloading) 성능을 최적화할 수 있는 기능을 사용할 수 있습니다. 사전 로딩(preloading)은 사용자가 컴포넌트를 사용하는 시점에 필요한 리소스를 미리 가져오는 방식입니다. 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.
External links also work, and automatically have these props: target="_blank" rel="noopener noreferrer"
.
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
탐색할 주소를 설정합니다. Example: /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/>
Rendering a <Redirect>
will navigate to a new location. 새로운 주소는 방문 기록 상 현재 주소를 덮어씁니다. 마치 서버에서 리다이렉트(HTTP 3xx)를 처리하는 것과 같습니다. 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" />;
};
@docusaurus/router
implements React Router and supports its features.
<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. 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/>
동적으로 표시되는 자리표시자(placeholder)를 포함한 텍스트를 위한 간단한 컴포넌트입니다.
자리표시자는 동적으로 처리되는 값과 여러분이 선택한 JSX 요소(문자열, 링크, 스타일 요소 등)을 대체합니다.
Props
children
: text containing interpolation placeholders like{placeholderName}
values
: object containing interpolation placeholder values
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. The <Translate>
component supports interpolation.
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]
.
The <Translate/>
props must be hardcoded strings.
Apart from the values
prop used for interpolation, it is not possible to use variables, or the static extraction wouldn't work.
Props
children
: untranslated string in the default site locale (can contain interpolation placeholders)id
: optional value to be used as the key in JSON translation filesdescription
: optional text to help the translatorvalues
: optional object containing interpolation placeholder values
Example
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>
);
}
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" />
Hooks
useDocusaurusContext
도큐사우루스 컨텍스트에 접근하기 위한 리액트 후크입니다. 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>;
};
사용 예:
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>
);
};
The siteConfig
object only contains serializable values (values that are preserved after JSON.stringify()
). 함수와 정규식 등은 클라이언트 쪽에서 손실됩니다.
useIsBrowser
Returns true
when the React app has successfully hydrated in the browser.
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.
사용 예:
import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
const MyComponent = () => {
const isBrowser = useIsBrowser();
return <div>{isBrowser ? 'Client' : 'Server'}</div>;
};
useBaseUrl
React hook to prepend your site baseUrl
to a string.
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
Options
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} />;
};
In most cases, you don't need useBaseUrl
.
Prefer a require()
call for assets:
<img src={require('@site/static/img/myImage.png').default} />
useBaseUrlUtils
Sometimes useBaseUrl
is not good enough. 여러분의 사이트 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
모든 플러그인에서 만든 도큐사우루스 전역 데이터에 접근하기 위한 리액트 후크입니다.
전역 데이터는 플러그인의 이름, ID로 네임스페이스가 지정됩니다.
플러그인 ID는 같은 사이트에서 플러그인을 여러 번 사용할 때만 유용합니다. 각 플러그인 인스턴스는 자신만의 전역 데이터를 만들 수 있습니다.
type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;
사용 예:
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>;
};
Inspect your site's global data at ./docusaurus/globalData.json
usePluginData
특정 플러그인 인스턴스에서 만든 전역 데이터에 접근합니다.
플러그인 전역 데이터에 접근하기 위해 가장 편리하고 많이 사용하는 후크입니다.
pluginId
is optional if you don't use multi-instance plugins.
function usePluginData(
pluginName: string,
pluginId?: string,
options?: {failfast?: boolean},
);
사용 예:
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};
useAllPluginInstancesData
특정 플러그인에서 만든 전역 데이터에 접근합니다. 플러그인 이름을 지정하면 같은 이름을 가지는 모든 플러그인 인스턴스의 데이터를 id별로 반환합니다.
function useAllPluginInstancesData(
pluginName: string,
options?: {failfast?: boolean},
);
사용 예:
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
interpolate
The imperative counterpart of the <Interpolate>
component.
Signature
// Simple string interpolation
function interpolate(text: string, values: Record<string, string>): string;
// JSX interpolation
function interpolate(
text: string,
values: Record<string, ReactNode>,
): ReactNode;
Example
import {interpolate} from '@docusaurus/Interpolate';
const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});
translate
The imperative counterpart of the <Translate>
component. Also supporting placeholders interpolation.
Use the imperative API for the rare cases where a component cannot be used, such as:
- the page
title
metadata - the
placeholder
props of form inputs - the
aria-label
props for accessibility
Signature
function translate(
translation: {message: string; id?: string; description?: string},
values: Record<string, string>,
): string;
Example
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>
);
}
Modules
ExecutionEnvironment
현재 렌더링 환경을 확인하기 위해 사용할 수 있는 몇 가지 상태 변수를 제공하는 모듈입니다.
For React rendering logic, use useIsBrowser()
or <BrowserOnly>
instead.
예:
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
Field | 설명 |
---|---|
ExecutionEnvironment.canUseDOM | true if on client/browser, false on Node.js/prerendering. |
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 . |
constants
클라이언트 측 테마 코드에 유용한 상수를 제공하는 모듈입니다.
import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';