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: add fallback prop to <PrismicRichText> which is rendered when given an empty field #135

Merged
merged 1 commit into from
Mar 17, 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
9 changes: 8 additions & 1 deletion src/PrismicRichText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@ export type PrismicRichTextProps = {
* @defaultValue `<a>`
*/
externalLinkComponent?: PrismicLinkProps["externalComponent"];

/**
* The value to be rendered when the field is empty. If a fallback is not
* given, `null` will be rendered.
*/
fallback?: React.ReactNode;
};

type CreateDefaultSerializerArgs = {
Expand Down Expand Up @@ -255,14 +261,15 @@ export const PrismicRichText = (

return <>{serialized}</>;
} else {
return null;
return props.fallback != null ? <>{props.fallback}</> : null;
}
}, [
props.field,
props.internalLinkComponent,
props.externalLinkComponent,
props.components,
props.linkResolver,
props.fallback,
context.linkResolver,
context.richTextComponents,
]);
Expand Down
25 changes: 25 additions & 0 deletions test/PrismicRichText.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,31 @@ test("returns null if passed an empty field", (t) => {
t.deepEqual(actualEmpty2, expected);
});

test("returns fallback if given when passed empty field", (t) => {
const fallback = <div>fallback</div>;
const actualNull = renderJSON(
<PrismicRichText field={null} fallback={fallback} />,
);
const actualUndefined = renderJSON(
<PrismicRichText field={undefined} fallback={fallback} />,
);
const actualEmpty = renderJSON(
<PrismicRichText field={[]} fallback={fallback} />,
);
const actualEmpty2 = renderJSON(
<PrismicRichText
field={[{ type: "paragraph", text: "", spans: [] }]}
fallback={fallback}
/>,
);
const expected = renderJSON(fallback);

t.deepEqual(actualNull, expected);
t.deepEqual(actualUndefined, expected);
t.deepEqual(actualEmpty, expected);
t.deepEqual(actualEmpty2, expected);
});

test("returns <h1> if type is heading1", (t) => {
const field: prismicT.RichTextField = [
{
Expand Down