Skip to content

Commit

Permalink
fix: render Rich Text line breaks as <br />
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed Oct 9, 2021
1 parent ba34318 commit 4eaa6dd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/PrismicRichText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,22 @@ const createDefaultSerializer = (
label: ({ node, children }) => (
<span className={node.data.label}>{children}</span>
),
span: ({ text }) => <>{text}</>,
span: ({ text, key }) => {
const result: React.ReactNode[] = [];

let i = 0;
for (const line of text.split("\n")) {
if (i > 0) {
result.push(<br key={`${i}__break`} />);
}

result.push(<React.Fragment key={`${i}__line`}>{line}</React.Fragment>);

i++;
}

return <React.Fragment key={key}>{result}</React.Fragment>;
},
});

/**
Expand Down
20 changes: 20 additions & 0 deletions test/PrismicRichText.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -472,3 +472,23 @@ test("returns <span /> with label className if type is label", (t) => {

t.deepEqual(actual, expected);
});

test("renders line breaks as <br />", (t) => {
const field: prismicT.RichTextField = [
{
type: prismicT.RichTextNodeType.paragraph,
text: "line 1\nline 2",
spans: [],
},
];

const actual = renderJSON(<PrismicRichText field={field} />);
const expected = renderJSON(
<p>
line 1<br />
line 2
</p>,
);

t.deepEqual(actual, expected);
});

0 comments on commit 4eaa6dd

Please sign in to comment.