Was this page helpful?

Set up Experiences SDK with React

Prerequisites

Please read through the installation guide to ensure you meet the prerequisites and have the Experiences SDK installed in your project before starting.

Create your first experience

This guide walks you through getting your first experience up and running. For this example, we integrate the @contentful/experiences-sdk-react to render the content of your webpage. Initially, this involves setting up a simple custom button component. The example app is built using Vite with Typescript, but the approach can easily be adapted to any standard React app. Depending on your specific setup, you might need to make slight adjustments to the code (such as for environment variables).

Create your component

In this example, we create a "Button" component. The component is a simple React component that renders a button with some text.

// src/components/Button.tsx
import React from 'react';

interface ButtonComponentProps {
  text: string;
}

export const Button: React.FC<ButtonComponentProps> = ({ text, ...experienceProps }) => {
  return <button {...experienceProps}>{ text }</button>;
};

To learn more about creating custom components for your experience, check out the register custom components guide.

Register your component

Next, your component needs to be registered with the Experiences SDK. This is done with the help of the defineComponents function which can be imported from the @contentful/experiences-sdk-react package. We suggest registering your components once at the startup of your application; for example in the index.tsx (or like) file.

// src/registeredComponents.ts

import { defineComponents } from '@contentful/experiences-sdk-react';
import { Button } from './components/Button';

defineComponents([
  {
    component: Button,
    definition: {
      id: 'button',
      name: 'Button',
      category: 'Custom Components',
      variables: {
        text: {
          displayName: 'Text',
          type: 'Text',
          defaultValue: 'Click me!',
        },
      },
    },
  },
]);

Above, we register the Button component and provide a component definition that Experiences use to help you configure the component in the editor. In the component definition, we specify the id and name of the component, the category (where it is displayed in the Components tab), and the variables it supports. We configure the text variable to be of type Text and provide a default value. This variable is editable in the Experiences and its value is passed down to the Button component as a prop.

To learn more about the component definitions and what features they provide, please refer to the Component definition schema.

Create a Contentful client

To fetch the experience, create a Contentful client. The client requires a few initialization variables. In our example, we pull these variables from environment variables. See documentation for the specific framework you use to learn how to use environment variables within it.

We recommend creating the client once in your application and reusing it across the components that need to access Experiences.

For more info on using the JavaScript library for CDA and CPA and how get access to the variables needed, refer to Getting Started with Contentful and JavaScript.

// src/contentfulClient.ts

import { createClient } from 'contentful';

export const client = createClient({
  // your space id
  space: import.meta.env.VITE_CTFL_SPACE_ID,
  // your environment id
  environment: import.meta.env.VITE_CTFL_ENV_ID,
  // Supported values: 'preview.contentful.com' or 'cdn.contentful.com',
  host: import.meta.env.VITE_CTFL_API_HOST,
  // needs to be access token if host = 'cdn.contentful.com' and preview token if 'preview.contentful.com'
  accessToken: import.meta.env.VITE_CTFL_TOKEN
});

Display the experience

The Experiences SDK uses the Contentful client to fetch the experience. The Experiences SDK includes helpful hooks, such as useFetchBySlug, which allows you to fetch an experience by its slug (configured in the settings tab for the experience) or the useFetchById, which fetches the experience by its ID.

The hooks return the experience object, which can be rendered using the ExperienceRoot component. The ExperienceRoot component defines where the experience controls the content that is rendered. With ExperienceRoot, you have the flexibility to either allow your team to build entire pages or limit them to modifying specific sections of a webpage. To use it, simply import the ExperienceRoot component from the SDK and place it on the page where you want the experience to be rendered.

// src/App.tsx
import { useParams } from "react-router-dom";

import {
  useFetchBySlug,
  ExperienceRoot,
  detachExperienceStyles
} from '@contentful/experiences-sdk-react'

import { client } from './contentfulClient.ts';
// trigger component registration
import './registeredComponents.ts';

const App = () => {
  // replace this section with however you choose to get your slug and locale (ex. from router, from internal state)
  const { slug = "home-page", locale } = useParams<{
    slug: string;
    locale?: string;
  }>();
  const localeCode = locale ?? "en-US";

  const { isLoading, error, experience } = useFetchBySlug({
    client,
    // id of the experience type (content type)
    experienceTypeId: import.meta.env.VITE_CTFL_EXPERIENCE_CONTENT_TYPE_ID,
    localeCode: locale,
    slug,
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>{error.message}</div>;
  }

  // optionally detach styles to have them on the page on initial render
  const experienceStyles = detachExperienceStyles(experience);

  return (
    <>
      <style>{experienceStyles}</style>
      <ExperienceRoot
        experience={experience}
        locale={locale}
      />
    </>
  );
}

export default App;

Start editing your experience

Now that your first experience is up and running, you can run your app and begin editing your experience from within the experience editor. To take your experience to the next level, check out our additional guides, such as registering custom components and registering design tokens.