Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): add fallback to BrowserOnly component #2665

Merged
merged 3 commits into from
Apr 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions packages/docusaurus/src/client/exports/BrowserOnly.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
import React from 'react';
import ExecutionEnvironment from './ExecutionEnvironment';

function BrowserOnly({children}) {
return (
ExecutionEnvironment.canUseDOM && children != null && <>{children()}</>
);
function BrowserOnly({children, fallback}) {
if (!ExecutionEnvironment.canUseDOM || children == null) {
return fallback || null;
}

return <>{children()}</>;
}

export default BrowserOnly;
5 changes: 3 additions & 2 deletions website/docs/docusaurus-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,15 @@ function Home() {

### `<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).
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.

```jsx
import BrowserOnly from '@docusaurus/BrowserOnly';

function MyComponent() {
return (
<BrowserOnly>
<BrowserOnly
fallback={<div>The fallback content to display on prerendering</div>}>
{() => {
// Something that should be excluded during build process prerendering.
}}
Expand Down