@prismicio/react - v3
Overview
@prismicio/react is the official Prismic package for creating React-based websites.
With this package, you can:
Display slice zones with custom components.
This page documents all APIs provided by @prismicio/react.
Install
@prismicio/react is installed when bootstrapping a Next.js project with @slicemachine/init.
npx @slicemachine/init@latestIt can also be manually installed in any React project:
npm install --save @prismicio/react @prismicio/client@prismicio/client is a peer dependency and must be installed.
API
All components can be imported as a named import.
The following example imports PrismicImage:
import { PrismicImage } from "@prismicio/react";<PrismicImage>
Displays an optimized image from an image field.
<PrismicImage field={slice.primary.image} />fieldImageFieldAn image field to display.
alt""fallbackAlt""Declare an image as decorative if the image field does not have alt text.
widthsnumber[] | "thumbnails" | "defaults"Widths used to build a srcset value for the image field.
"thumbnails"uses the image field’s thumbnails."defaults"uses[640, 750, 828, 1080, 1200, 1920, 2048, 3840].
Only one of widths or pixelDensities can be used.
"defaults"
pixelDensitiesnumber[] | "defaults"Pixel densities used to build a srcset value for the image field.
"defaults"uses[1, 2, 3].
Only one of widths or pixelDensities can be used.
fallbackReactNodeRendered if the image is empty.
<PrismicLink>
Displays a link from a link field or Prismic document.
<PrismicLink field={slice.primary.link} />fieldLinkFieldA link field to link. Only one of field, document, or href can be
used.
documentPrismicDocumentA Prismic document to link. Only one of field, document, or href can
be used.
hrefstringA URL to link. Only one of field, document, or href can be used.
relundefined | string | ((metadata) => string | undefined)A ref attribute. A function can be passed to determine the value based
on the link. Use undefined to remove the rel attribute.
"noreferrer" if the link is external.
linkResolver(field: ContentRelationshipField) => string | null | undefinedA link resolver function used to
determine a URL from the field or document prop. If it returns a
value, it takes priority over a route resolver.
internalComponentComponentTypeThe component used to render internal links.
<a>
externalComponentComponentTypeThe component used to render external links.
<a>
<PrismicText>
Displays plain text from a rich text field.
<PrismicText field={slice.primary.text} />fieldRichTextFieldA rich text field to render.
fallbackstringRendered if the rich text field is empty.
separatorstringSeparator used between text blocks.
" "
<PrismicRichText>
Displays formatted text from a rich text field.
<PrismicRichText field={slice.primary.text} />fieldRichTextFieldA rich text field to render.
fallbackReactNodeRendered if the rich text field is empty.
componentsobjectA map of rich text block types to React components. The available heading types are heading1 to heading6. The available block types are paragraph, preformatted, list, oList, listItem, oListItem, image, and embed. The available inline types are strong, em, hyperlink, label, and span. See an example.
Standard HTML elements (e.g. heading1 becomes a <h1>).
linkResolver(field: ContentRelationshipField) => string | null | undefinedA link resolver function used to
determine a URL from the field or document prop. If it returns a
value, it takes priority over a route resolver.
internalLinkComponentComponentTypeThe component used to render internal links.
<a>
internalLinkComponentComponentTypeThe component used to render external links.
<a>
<PrismicTable>
Displays a formatted table from a table field.
<PrismicTable field={slice.primary.my_table_field} />fieldTableFieldA table field to render.
fallbackReactNodeRendered if the table field is empty.
componentsobjectA map of table elements and rich text block types to React components. The
available table elements are table, thead, tbody, tr, th, and
td. The available rich text block types are paragraph, em, strong,
and hyperlink. See an example.
Standard HTML elements (e.g. table becomes a <table>).
<SliceZone>
Renders slices from a slice zone.
<SliceZone
slices={doc.data.slices}
components={{
text: ({ slice }) => (
<section>
<PrismicRichText field={slice.primary.text} />
</section>
),
}}
/>slicesSliceZonecomponentsRecord<string, ComponentType<SliceComponentProps>>A map of slice types to React components.
sliceSliceThe slice object being displayed.
slicesSlice[]All slices in the slice zone.
indexnumberThe index of the slice in the slice zone.
contextunknownThe data passed to <SliceZone>’s context prop.
defaultComponentComponentTypeRendered if a slice does not have a component mapping.
contextanyArbitrary data made available to all slice components.
<PrismicToolbar>
Adds the Prismic toolbar.
<PrismicToolbar repositoryName="example-prismic-repo" />repositoryNamestringThe name of the Prismic repository.
Upgrade from v2
Follow these steps to upgrade an existing project to @prismicio/react v3.
Install
@prismicio/reactv3npm install @prismicio/react@^3Create a custom
<PrismicRichText>Create a custom
<PrismicRichText>component with your default props. Use the custom component in place of@prismicio/react’s version.src/components/PrismicRichText.tsximport { PrismicRichText as BasePrismicRichText, PrismicRichTextProps, JSXMapSerializer, } from "@prismicio/react"; const defaultComponents: JSXMapSerializer = { heading1: ({ children }) => ( <h1 className="font-bold text-3xl">{children}</h1> ), }; export function PrismicRichText({ components, ...props }: PrismicRichTextProps) { return ( <BasePrismicRichText components={{ ...defaultComponents, ...components }} {...props} /> ); }Create a custom
<PrismicLink>Create a custom
<PrismicLink>component with your default props. Use the custom component in place of@prismicio/react’s version.src/components/PrismicLink.tsximport { PrismicLink as BasePrismicLink, PrismicLinkProps, LinkProps, } from "@prismicio/react"; function InternalLink(props: LinkProps) { return <a className="internal" {...props} />; } export function PrismicLink(props: PrismicLinkProps) { return <BasePrismicLink internalComponent={InternalLink} {...props} />; }Replace
usePrismicClient()Use a reference to a client instead.
import { client } from "../prismicio"; function Example() { // Use the imported `client` instead. const client = usePrismicClient(); return <div>An example component</div>; }We recommend exporting a client from a root-level file named
prismicio.ts.prismicio.tsimport { createClient } from "@prismicio/client"; export const client = createClient("example-prismic-repo");Replace
usePrismicPreviewResolver()Use
client.resolvePreviewURL()and your router’s redirect function instead.import { redirect } from "react-router"; import { useEffect } from "react"; import { client } from "../prismicio"; function PreviewPage() { usePrismicPreviewResolver({ navigate: redirect }); useEffect(() => { client .resolvePreviewURL({ defaultURL: "/" }) .then((url) => redirect(url)); }, []); return <div>Loading...</div>; }Replace all query hooks
Use a query library with a Prismic client, such as TanStack Query.
import { usePrismicDocumentByUID } from "@prismicio/react"; import { useQuery } from "@tanstack/react-query"; import { client } from "../prismicio"; function Home() { const [page] = usePrismicDocumentByUID("page", "home"); const { data } = useQuery({ queryKey: ["home"], queryFn: () => client.getByUID("page", "home"), }); return <h1>{data?.data.title}</h1>; }Refer to the following table for each hook’s replacement client method.
Hook Query method usePrismicDocuments()client.get()useFirstPrismicDocument()client.getFirst()useAllPrismicDocumentsDangerously()client.dangerouslyGetAll()usePrismicDocumentByID()client.getByID()usePrismicDocumentsByIDs()client.getByIDs()useAllPrismicDocumentsByIDs()client.getAllByIDs()usePrismicDocumentByUID()client.getByUID()usePrismicDocumentsByUIDs()client.getByUIDs()useAllPrismicDocumentsByUIDs()client.getAllByUIDs()useSinglePrismicDocument()client.getSingle()usePrismicDocumentsByType()client.getByType()useAllPrismicDocumentsByType()client.getAllByType()usePrismicDocumentsByTag()client.getByTag()useAllPrismicDocumentsByTag()client.getAllByTag()usePrismicDocumentsBySomeTags()client.getBySomeTags()useAllPrismicDocumentsBySomeTags()client.getAllBySomeTags()usePrismicDocumentsByEveryTag()client.getByEveryTag()useAllPrismicDocumentsByEveryTag()client.getAllByEveryTag()Remove
<PrismicProvider><PrismicProvider>is no longer included.import { PrismicProvider } from "@prismicio/react"; function App({ children }) { return ( <PrismicProvider client={client}> // [!code --] {children} </PrismicProvider> ); }