Skip to content

Commit

Permalink
feat: add fallback prop to <PrismicRichText> which is rendered wh…
Browse files Browse the repository at this point in the history
…en given an empty field (#135)
  • Loading branch information
angeloashmore authored Mar 17, 2022
1 parent 3aeeda5 commit 1c6eacb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
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

0 comments on commit 1c6eacb

Please sign in to comment.