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 text content not rendered on ssr #4798

Merged
merged 1 commit into from
Jan 22, 2022
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
5 changes: 5 additions & 0 deletions .changeset/rude-humans-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Fix text not rendered on ssr
16 changes: 15 additions & 1 deletion packages/slate-react/src/components/string.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ const TextString = (props: { text: string; isTrailing?: boolean }) => {

const ref = useRef<HTMLSpanElement>(null)

const getTextContent = () => {
return `${text ?? ''}${isTrailing ? '\n' : ''}`
}

// This is the actual text rendering boundary where we interface with the DOM
// The text is not rendered as part of the virtual DOM, as since we handle basic character insertions natively,
// updating the DOM is not a one way dataflow anymore. What we need here is not reconciliation and diffing
Expand All @@ -72,7 +76,7 @@ const TextString = (props: { text: string; isTrailing?: boolean }) => {
// useLayoutEffect: updating our span before browser paint
useIsomorphicLayoutEffect(() => {
// null coalescing text to make sure we're not outputing "null" as a string in the extreme case it is nullish at runtime
const textWithTrailing = `${text ?? ''}${isTrailing ? '\n' : ''}`
const textWithTrailing = getTextContent()

if (ref.current && ref.current.textContent !== textWithTrailing) {
ref.current.textContent = textWithTrailing
Expand All @@ -82,6 +86,16 @@ const TextString = (props: { text: string; isTrailing?: boolean }) => {
// as this effectively replaces "specifying the text in the virtual DOM under the <span> below" on each render
})

// Render text content immediately if it's the first-time render
// Ensure that text content is rendered on server-side rendering
if (!ref.current) {
return (
<span data-slate-string ref={ref}>
{getTextContent()}
</span>
)
}

// the span is intentionally same on every render in virtual DOM, actual rendering happens in the layout effect above
return <span data-slate-string ref={ref} />
}
Expand Down