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

Fix SimpleMarkdownText with SSR #3667

Merged
merged 1 commit into from
Jun 6, 2024
Merged
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
31 changes: 22 additions & 9 deletions packages/@ourworldindata/components/src/SimpleMarkdownText.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from "react"
import { computed } from "mobx"
import { Remark } from "react-remark"
import { Remark, useRemarkSync, UseRemarkSyncOptions } from "react-remark"
import { remarkPlainLinks } from "./markdown/remarkPlainLinks.js"
import visit from "unist-util-visit"

Expand Down Expand Up @@ -35,6 +35,17 @@ function transformDodLinks() {
}
}

function RemarkSync({
children,
...props
}: { children: string } & UseRemarkSyncOptions) {
return useRemarkSync(children, props)
}

// NOTE: We currently don't need to render markdown in React. We should be able
// to render it only during baking/on the server and pass the HTML as string.
// This way we could reduce the bundle size by not including a markdown library
// and improve performance.
export class SimpleMarkdownText extends React.Component<SimpleMarkdownTextProps> {
@computed get text(): string {
return this.props.text
Expand All @@ -58,14 +69,16 @@ export class SimpleMarkdownText extends React.Component<SimpleMarkdownTextProps>
}

render(): React.ReactElement | null {
return (
<Remark
rehypePlugins={[transformDodLinks]}
remarkPlugins={[remarkPlainLinks]}
rehypeReactOptions={this.rehypeReactOptions}
>
{this.text}
</Remark>
const isServer = typeof window === "undefined"
const options = {
rehypePlugins: [transformDodLinks],
remarkPlugins: [remarkPlainLinks],
rehypeReactOptions: this.rehypeReactOptions,
}
return isServer ? (
<RemarkSync {...options}>{this.text}</RemarkSync>
) : (
<Remark {...options}>{this.text}</Remark>
)
}
}
Expand Down