@prismicio/react - v2

Overview

@prismicio/react is the official Prismic package for creating web apps with Prismic and React.

The package is formerly known as 'prismic-reactjs'

@prismicio/react used to be called prismic-reactjs. The latter is now deprecated, and you can replace it with @prismicio/react.

Find the documentation for prismic-reactjs on npm.

Dependencies and requirements

This package can only be used in a React project. It relies on @prismicio/client and @prismicio/helpers as peer dependencies.

Since this is a general-purpose React library, it can be used in setups like Create React App and Vite or in more advanced frameworks that use React like Next.js and Gatsby.

Installation

Install packages

Add @prismicio/react and its peer dependencies to your React project via the command line:

  • npm
  • Yarn
npm
Copy
npm install @prismicio/react @prismicio/client @prismicio/helpers
Yarn
Copy
yarn add @prismicio/react @prismicio/client @prismicio/helpers

Create an optional Link Resolver

Create a Link Resolver function. This is one of two ways to tell React how to handle internal links in Prismic documents. (The other way to do so is with a Route Resolver, which works better for more complex routes. Read a comparison.)

A Link Resolver function takes a document from Prismic as an argument and returns the URL path for that document. Here's a basic example of a linkResolver.js file:

Copy
export function linkResolver(document) {
  if (document.type === "post") {
    return "/blog/" + document.uid;
  }

  return "/";
}

Create context with <PrismicProvider>

Add the Prismic provider component to the root of your React app. The provider allows settings for @prismicio/react's React components to be configured in one central location. This is done using React context.

Here's an example of setting up the context:

Copy
import { PrismicProvider } from "@prismicio/react";

import { linkResolver } from "./linkResolver";

function App({ children }) {
  return (
    <PrismicProvider linkResolver={linkResolver}>
      {children}
    </PrismicProvider>
  );
}

Additional options for <PrismicProvider> for specific components are described below.

Usage

@prismicio/react provides two main functionalities:

  • Components: It provides a collection of components to render content from Prismic documents.
  • Client hooks: It provides React hooks to query content from a Prismic repository.

For client-rendered pages

The hooks are designed for client-rendered React apps or pages. If you are using a React framework with server-side rendering (like Next.js) or static data fetching (like Gatsby), prefer the framework's standard data fetching practices over these hooks.

Each query method from a Prismic client, such as getAllByType or getSingle, is provided as a hook.

Copy
const [documents] = useAllPrismicDocumentsByType("page");
const [settingsDocument] = useSinglePrismicDocument("settings");

Hooks return the fetching state in addition to the query result. This allows you to render, for example, a "loading" interface while the client is fetching results.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByType("page")

state can be one of the following values:

  • "idle": The hook is waiting to query the repository.
  • "loading": The hook is querying the repository.
  • "loaded": The hook is done querying the repository.
  • "failed": The hook failed to query the repository.

error will contain a PrismicError object from @prismic/client if the hook fails to query the repository. The hook will be in the failed state.

All hooks use a client object, created from @prismicio/client and provided to <PrismicProvider> at the root of your React app. See the @prismicio/client Technical Reference for configuration options.

Copy
import * as prismic from "@prismicio/client";
import { PrismicProvider } from "@prismicio/react";

const endpoint = prismic.getEndpoint("repo-name");
const client = prismic.createClient(endpoint);

function App({ children }) {
  return (
    <PrismicProvider client={client}>
      {children}
    </PrismicProvider>
  );
}

If a hook requires specific parameters or a different client, they can be provided as an object in the last argument.

Copy
const endpoint = prismic.getEndpoint("repo-name");
const newClient = prismic.createClient(endpoint);

const [documents] = useAllPrismicDocumentsByType("page", {
  client: newClient,
  lang: "fr-fr"
});

Here are all of the components and hooks:

<PrismicProvider>

Copy
import { PrismicProvider } from "@prismicio/react";

A React component to provide settings for Prismic's React components, using React context. All @prismicio/react components that are children of this one will receive the specified options as defaults.

Copy
<PrismicProvider client={client} >
  {children}
</PrismicProvider>

<PrismicProvider> accepts the following props:

client

An initialized Prismic API client from the @prismicio/client package.

linkResolver

A function that takes a document from Prismic as an argument and returns the URL path for that document. See the Link Resolver documentation.

richTextComponents

A map or function that returns a React component for a given Rich Text element. See the <PrismicRichText> section for more detail.

internalLinkComponent

A component for handling internal links. See the section on <PrismicLink> for more detail.

externalLinkComponent

A component for handling external links. See the section on <PrismicLink> for more detail.

<PrismicRichText>

Copy
import { PrismicRichText } from "@prismicio/react";

A React component that renders content from a Prismic Rich Text or Title field.

By default, HTML elements are rendered for each piece of content. For example, a heading1 block will render an <h1> HTML element. Links will use <PrismicLink> by default.

Copy
<PrismicRichText field={document.data.myRichTextField} />

A fallback prop can be provided to define what to render when the Rich Text or Title field is empty. If a fallback prop is not provided, null is rendered by default for an empty field.

Copy
<PrismicRichText
  field={document.data.myRichTextField}
  fallback={<p>No content</p>}
/>

This component returns a React fragment with no wrapping element around the content. If you need a wrapper, add a component around <PrismicRichText>.

Copy
<article>
  <PrismicRichText field={document.data.myRichTextField} />
</article>

To customize the components that are rendered for each block type, provide a map or function that returns a component to the components prop.

Copy
<PrismicRichText
  field={document.data.myRichTextField}
  components={{
    heading1: ({ children }) => <Heading>{children}</Heading>,
    paragraph: ({ children }) => <p className="paragraph">{children}</p>,
  }}
/>

Components can also be provided in a centralized location using the <PrismicProvider> React context provider. All <PrismicRichText> components will use the shared component mapping automatically.

Copy
function App({ children }) {
  return (
    <PrismicProvider
      richTextComponents={{
        heading1: ({ children }) => <Heading>{children}</Heading>,
        paragraph: ({ children }) => <p className="paragraph">{children}</p>,
      }}
    >
      {children}
    </PrismicProvider>
  );
}

If a different component needs to be rendered for a specific instance of <PrismicRichText>, a components prop can be provided to override the shared component mapping.

<PrismicText>

Copy
import { PrismicText } from "@prismicio/react";

React component that renders content from a Prismic Rich Text or Title field as plain text.

Copy
<PrismicText field={document.data.myTitleField} />

A fallback prop can be provided to define what to render when the Rich Text or Title field is empty. If a fallback prop is not given, null is rendered by default for an empty field.

Copy
<PrismicText field={document.data.myTitleField} fallback="Untitled" />

This component returns a React fragment with no wrapping element around the content. If you need a wrapper, add a component around <PrismicRichText>.

Copy
<h1>
  <PrismicText field={document.data.myTitleField} />
</h1>

<PrismicLink>

Copy
import { PrismicLink } from "@prismicio/react";

React component that renders a link from a Prismic Link field or a Prismic document.

It automatically resolves a field's link to a URL. It also applies the correct target and rel props if "Open in new tab" is enabled for the field.

Copy
<PrismicLink field={document.data.myLinkField}>
  Click me
</PrismicLink>

To link to a document, use the document prop in place of the field prop.

Copy
<PrismicLink document={document}>
  Click me
</PrismicLink>

By default, an <a> HTML element is rendered for all links. If your React app requires a special <Link> component for internal links, such as one from react-router-dom, a component can be provided to the internalComponent prop. That component will automatically be rendered for internal links.

Copy
<PrismicLink
  field={document.data.myLinkField}
  internalComponent={Link}
>
  Click me
</PrismicLink>

The component for external links can similarly be overridden using the externalComponent prop.

Copy
<PrismicLink
  field={document.data.myLinkField}
  externalComponent={(props) => <a className="external" {...props} />}
>
  Click me
</PrismicLink>

An internal and external link component can also be provided in a centralized location using the <PrismicProvider> React context provider. All <PrismicLink> components will use the components automatically.

Copy
function App({ children }) {
  return (
    <PrismicProvider
      internalLinkComponent={Link}
      externalComponent={(props) => <a className="external" {...props} />}
    >
      {children}
    </PrismicProvider>
  );
}

If your app uses the Route Resolver when querying for documents, providing a Link Resolver is optional. If your app does not use Route Resolvers, or requires overriding a document's URL in specific cases, a Link Resolver can be provided using the linkResolver prop.

Copy
<PrismicLink
  field={document.data.myLinkField}
  linkResolver={linkResolver}
>
  Click me
</PrismicLink>

A Link Resolver can also be provided in a centralized location using the <PrismicProvider> React context provider. All <PrismicLink> components will use the shared Link Resolver automatically.

Copy
function App({ children }) {
  return (
    <PrismicProvider linkResolver={linkResolver}>
      {children}
    </PrismicProvider>
  );
}

If a different Link Resolver needs to be used for a specific instance of <PrismicLink>, a linkResolver prop can be provided to override the shared Link Resolver.

<PrismicLink> accepts an href prop if you have a URL that does not come from a Prismic Link field or document. You can use this component for all links in your app if you want to take advantage of the automatic internal/external component and target prop functionality.

Copy
<PrismicLink href="/my-url">
  Click me
</PrismicLink>

<PrismicImage>

Copy
import { PrismicImage } from '@prismicio/react'

React component that renders an optimized image from a Prismic Image field. The rendered <img> element contains a srcset with image URLs for common viewport widths.

Copy
<PrismicImage field={doc.data.myImageField} />

Are you using a framework like Next.js or Gatsby?

If you are using a framework like Next.js or Gatsby, prefer its framework-specific image integration over this <PrismicNext>. For example, use @prismicio/next's <PrismicNextImage> component or Gatsby's gatsby-plugin-image component if you are using those frameworks.

Only use <PrismicImage> if your environment does not have a built-in optimized image component.

The image CDN which Prismic serves all images through, imgix, allows image transformations using URL parameters. imgix URL parameters can be provided to <PrismicImage> using the imgixParams prop.

Copy
// Renders a grayscale image
<PrismicImage field={doc.data.myImageField} imgixParams={{ sat: -100 }} />

See imgix's Image URL API Reference for a full list of the available parameters, including saturation changes, cropping, and blurring.

The component automatically applies the Image field’s alt text to the rendered <img> element. To customize the alt text, use the alt prop.

Copy
<PrismicImage field={doc.data.imageField} alt="" />

To provide a fallback alt text to be used if the Image field does not contain alt text, use the fallbackAlt prop.

Copy
<PrismicImage field={doc.data.imageField} fallbackAlt="" />

Note: The alt and fallbackAlt props only accept an empty string ("") to let you declare an image as decorative. Any other value is invalid. See the alt must be an empty string” article for more details.

By default, <PrismicImage> will use the following widths in its srcset attribute: 640, 750, 828, 1080, 1200, 1920, 2048, 3840. To override these widths, use the widths prop.

Copy
<PrismicImage field={doc.data.imageField} widths={[400, 800, 1600]} />

To use a pixel density-based srcset instead, pass a set of pixel densities to the pixelDensities prop.

Copy
<PrismicImage field={doc.data.imageField} pixelDensities={[2, 4]} />

To use the built-in set of good default pixel densities, pass pixelDensities="defaults" to the component. The component uses [1, 2, 3] as its default pixel densities.

Copy
<PrismicImage field={doc.data.imageField} pixelDensities="defaults" />

<SliceZone>

Copy
import { SliceZone } from "@prismicio/react";

React component that renders content from a Prismic Slice Zone using React components for each type of Slice.

For example, if a Slice Zone contains a Text Slice followed by an Images Slice, <SliceZone> will render <TextSlice> and <ImagesSlice> in a list.

Copy
<SliceZone
  slices={document.data.body}
  components={{
    text: TextSlice,
    images: ImagesSlice,
  }}
/>

Alongside the slices prop, an object of Slice type IDs (for example: "text") mapped to its React component (for example: <TextSlice>) should be provided to the components prop.

Slice components receive four props:

  • slice: The Slice object being rendered.
  • index: The index of the Slice within the Slice Zone.
  • slices: The list of all Slice objects in the Slice Zone.
  • context: Arbitrary data passed to the <SliceZone>'s context prop.

A Slice component could look like this:

Copy
function TextSlice({ slice }) {
  return (
    <section>
      <PrismicRichText field={slice.primary.text} />
    </section>
  );
}

If you have data that needs to be shared with all Slice components, provide a value to the context prop. The prop will be passed to each Slice component.

Copy
<SliceZone
  slices={document.data.body}
  components={{
    text: TextSlice,
    images: ImagesSlice,
  }}
  context={{ foo: "bar" }}
/>

By default, a "TODO" component will be rendered with a warning if a component is not provided for a Slice type. To override the default component, provide a component to the defaultComponent prop. The default component is passed the same props listed above.

Copy
<SliceZone
  slices={document.data.body}
  defaultComponent={() => null}
/>

The default "TODO" component will not be rendered in production (i.e. when process.env.NODE_ENV is production).

This component returns a React fragment with no wrapping element around the list of Slice components. If you need a wrapper, add a component around <SliceZone>.

Copy
<article>
  <SliceZone
    slices={document.data.body}
    components={{
      text: TextSlice,
      images: ImagesSlice,
    }}
  />
</article>

To optimize the performance of <SliceZone>, prefer defining the components prop using a variable defined outside the component.

Copy
const components = {
  text: TextSlice,
  images: ImagesSlice,
};

function Page() {
  return (
    <SliceZone
      slices={document.data.body}
      components={components}
    />
  );
}

Upgrading from next-slicezone

<SliceZone> from @prismicio/react replaces the component from the next-slicezone package. If you are currently using next-slicezone with a resolver prop, you can still pass that prop to the updated component.

<SliceZone
  slices={document.data.body}
  resolver={({ sliceName }) => {
    switch (sliceName) {
      case 'text':
        return TextSlice

      case 'images':
        return ImagesSlice
    }
  }}
/>

The resolver prop is deprecated and will be removed in a future major release. Please upgrade to the component prop using the object format described above.

<PrismicToolbar>

Copy
import { PrismicToolbar } from "@prismicio/react";

React component that injects the Prismic Toolbar into the app.

This component can be placed anywhere in the React tree. The Prismic Toolbar script will be appended to the end of the app's <body> element.

Copy
<PrismicToolbar repositoryName="repo-name" />

If your repository requires the legacy Prismic Toolbar, provide a type prop to use the legacy script. By default, type is set to "new".

Copy
<PrismicToolbar repositoryName="repo-name" type="legacy" />

usePrismicDocuments(params)

A hook that queries the Prismic repository for a paginated list of documents.

This hook accepts the same arguments as the client's get method.

Copy
const [documents, { state, error }] = usePrismicDocuments();

useFirstPrismicDocument(params)

A hook that queries content from the Prismic repository and returns only the first result, if any.

This hook accepts the same arguments as the client's getFirst method.

Copy
const [document, { state, error }] = useFirstPrismicDocument();

useAllPrismicDocuments(params)

A hook that queries content from the Prismic repository and returns all matching content. If no predicates are provided, all documents will be fetched.

This hook accepts the same arguments as the client's getAll method.

Copy
const [documents, { state, error }] = useAllPrismicDocuments();

usePrismicDocumentByID(id, params)

A hook that queries a document from the Prismic repository with a specific ID.

This hook accepts the same arguments as the client's getByID method.

Copy
const [document, { state, error }] = usePrismicDocumentByID("id");

usePrismicDocumentsByIDs(arrayOfIDs, params)

A hook that queries the Prismic repository for a paginated list of documents with specific IDs, returning the documents in the order of the provided IDs.

This hook accepts the same arguments as the client's getByIDs method.

Copy
const [documents, { state, error }] = usePrismicDocumentsByIDs(["id1", "id2"]);

useAllPrismicDocumentsByIDs(arrayOfIDs, params)

A hook that queries all documents from the Prismic repository with specific IDs, returning the documents in the order of the provided IDs.

This hook accepts the same arguments as the client's getByIDs method.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByIDs(["id1", "id2"]);

usePrismicDocumentByUID(documentType, uid, params)

A hook that queries a document from the Prismic repository with a specific UID and Custom Type.

This hook accepts the same arguments as the client's getByUID method.

Copy
const [document, { state, error }] = usePrismicDocumentByUID("page", "uid");

usePrismicDocumentsByUIDs(documentType, arrayOfUIDs, params)

A hook that queries the Prismic repository for a paginated list of documents with specific UIDs of a Custom Type, returning the documents in the order of the provided UIDs.

This hook accepts the same arguments as the client's getByUIDs method.

Copy
const [documents, { state, error }] = usePrismicDocumentsByUIDs("page", ["uid1", "uid2"]);

useAllPrismicDocumentsByUIDs(documentType, arrayOfUIDs, params)

A hook that queries all documents from the Prismic repository with specific UIDs of a Custom Type, returning the documents in the order of the provided UIDs.

This hook accepts the same arguments as the client's getAllByUIDs method.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByUIDs("page", ["uid1", "uid2"]);

useSinglePrismicDocument(documentType, params)

A hook that queries a singleton document from the Prismic repository for a specific Custom Type.

This hook accepts the same arguments as the client's getSingle method.

Copy
const [document, { state, error }] = useSinglePrismicDocument("settings");

usePrismicDocumentsByType(documentType, params)

A hook that queries the Prismic repository for a paginated list of documents from a specific Custom Type.

This hook accepts the same arguments as the client's getByType method.

Copy
const [documents, { state, error }] = usePrismicDocumentsByType("page");

useAllPrismicDocumentsByType(documentType, params)

A hook that queries all documents from the Prismic repository for a specific Custom Type.

This hook accepts the same arguments as the client's getAllByType method.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByType("page");

usePrismicDocumentsByTag(tag, params)

A hook that queries the Prismic repository for a paginated list of documents with a specific tag.

This hook accepts the same arguments as the client's getByTag method.

Copy
const [documents, { state, error }] = usePrismicDocumentsByTag("fruit");

useAllPrismicDocumentsByTag(tag, params)

A hook that queries all documents from the Prismic repository with a specific tag.

This hook accepts the same arguments as the client's getAllByTag method.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByTag("fruit");

usePrismicDocumentsByTags(arrayOfTags, params)

A hook that queries the Prismic repository for a paginated list of documents that have all of the provided tags.

This hook accepts the same arguments as the client's getByTags method.

Copy
const [documents, { state, error }] = usePrismicDocumentsByTags(["fruit", "vegetable"]);

useAllPrismicDocumentsByTags(arrayOfTags, params)

A hook that queries the Prismic repository for all documents that have all of the provided tags.

This hook accepts the same arguments as the client's getAllByTags method.

Copy
const [documents, { state, error }] = useAllPrismicDocumentsByTags(["fruit", "vegetable"]);

usePrismicClient()

A hook that returns the Prismic client provided to <PrismicProvider> at the root of your React app.

Copy
const client = usePrismicClient();

Any client methods not wrapped by @prismicio/react's hooks can be called directly on the client. For example, getting a list of all tags can be performed like this:

Copy
function MyComponent() {
  const [tags, setTags] = React.useState();
  const client = usePrismicClient();

  React.useEffect(() => {
    client.getTags().then((tags) => setTags(tags));
  }, [client]);
}

usePrismicPreviewResolver(params)

A hook that returns the URL of a previewed document during a preview session. This hook should be used on your React app's preview resolver page.

Copy
const [resolvedURL, { state, error }] = usePrismicPreviewResolver()

The hook will automatically read the preview session's URL parameters to resolve the previewed document's URL.

If you pass a navigate option, the hook will automatically redirect the browser to the resolved URL. The navigate option should be a function that accepts a URL string and redirects the browser. Popular client-side routing libraries like React Router provide this function to you.

Copy
import { useNavigate } from 'react-router-dom'

const navigate = useNavigate()

usePrismicPreviewResolver({ navigate })

Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.