Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@builder.io/react

BuilderIO307.3kMIT8.2.3TypeScript support: included

NOTE: If you want to register your React Server Components as custom components in Builder, you will need to use our experimental NextJS SDK here.

readme

Builder.io React SDK

NOTE: If you want to register your React Server Components as custom components in Builder, you will need to use our experimental NextJS SDK here.

Integration

See our full getting started docs, or jump right into integration. We generally recommend to start with page building as your initial integration:

Integrate Page Building Integrate Section Building Integrate CMS Data
CTA to integrate page building CTA to integrate section building CTA to integrate CMS data

React API

Simple example

The gist of using Builder, is fetching content (using queries on custom fields and targeting. Builder is structured like a traditional headless CMS where you can have different content types, called models. By default, every Builder space has a "page" model.

import { builder } from '@builder.io/react'

const API_KEY = '...' // Your Builder public API key
const MODEL_NAME = 'page';

const content = await builder
  .get(MODEL_NAME, {
    // Optional custom query
    query: {
      'data.customField.$gt': 100,
    },
    // Optional custom targeting
    userAttributes: {
      urlPath: '/' // Most Builder content is targeted at least by the URL path
    }
  })
  .promise()

// Later, pass the fetched content to the BuilderComponent
<BuilderComponent model={MODEL_NAME} content={content} />

The builder content is simply json that you pass to a <BuilderComponent /> to render. Learn more about it here

You can view all of the options for builder.get for fetching content in our full reference here

For example, with Next.js, to render Builder as your homepage:

export const getStaticProps = async () => {
  return {
    props: {
      builderContent: await builder
        .get('page', {
          userAttributes: {
            urlPath: '/', // Fetch content targeted to the homepage ("/" url)
          },
        })
        .promise(),
    },
  };
};

export default function MyHomePage({ builderContent }) {
  return (
    <>
      <YourHeader />
      <BuilderComponent model="page" content={builderContent} />
      <YourFooter />
    </>
  );
}

You can also allow dynamic page building (the ability to create new pages on new URLs dynamically). E.g. see this guide on how to do that

Registering Components

One of Builder's most powerful features is registering your own components for use in the drag and drop editor. You can choose to have these compliment the built-in components, or to be the only components allowed to be used (e.g. via components-only mode)

import { Builder } from '@builder.io/sdk-react';

function MyHero(props) {
  /* Your own hero component in your codebase */
}

Builder.registerComponent(MyHero, {
  name: 'Hero',
  inputs: [
    { name: 'title', type: 'string' }, // Gets passed as the `title` prop to the Hero
  ],
});

Learn more about registering components in Builder

BuilderComponent

You can find the full reference docs for the BuilderComponent props here

const MODEL_NAME = 'page';

// Render
<BuilderComponent model={MODEL_NAME} content={builderJson} />;

See our guides for Gatsby and Next.js for guides on using with those frameworks

Passing data and functions down

You can also pass data and functions down to the Builder component to use in the UIs (e.g. bind data values to UIs e.g. for text values or iterating over lists, and actions to trigger for instance on click of a button)

All data passed down is available in Builder actions and bindings as state.*, for instance in the below example state.products, etc will be available

<BuilderComponent
  model="page"
  data={{
    products: productsList,
    foo: 'bar',
  }}
  content={builderJson}
/>

You can also pass down functions, complex data like custom objects and libraries you can use context. Similar to React context, context passes all the way down (e.g. through symbols, etc). This data is not observed for changes and mutations

<BuilderComponent
  model="page"
  context={{
    addToCart: () => myService.addToCart(currentProduct),
    lodash: lodash,
  }}
  content={builderJson}
/>

Context is available in actions and bindings as context.*, such as context.lodash or context.myFunction() in the example above

Passing complex data

Everything passed down is available on the state object in data and actions - e.g. state.products[0].name

See more about using data passed down here

Builder

The global Builder singleton has a number of uses. Most important is registering custom components.

import * as React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { Builder } from '@builder.io/react';

class CodeBlockComponent extends React.Component {
  render() {
    return <SyntaxHighlighter language={this.props.language}>{this.props.code}</SyntaxHighlighter>;
  }
}

Builder.registerComponent(CodeBlockComponent, {
  name: 'Code Block',
  inputs: [
    {
      name: 'code',
      type: 'string',
      defaultValue: 'const incr = num => num + 1',
    },
    {
      name: 'language',
      type: 'string',
      defaultValue: 'javascript',
    },
  ],
});

See our full guide on registering custom components here.

See the full reference docs for registerComponent options here.

BuilderContent

Usage with Data Models

Although you can already fetch data models from our Content API directly and use it as you would any other API resource, with a BuilderContent component you are able to use live Editing / Previewing / A/B testing of your Data Models within the Builder Visual Editor.

Example, setting up an editable theme:
 <BuilderContent model="site-settings"> { (data, loading) => {
   If (loading) {
     return <Spinner />
   }
   return <>
      /*pass values down to an example ThemeProvider, used as a wrapper in your application*/
       <ThemeProvider theme={data.theme} >
           {props.children}
       </ThemeProvider>
   </>
   }}
</BuilderContent>

Or an example fetching server side and passing the content using the content prop, e.g. in Next.js

export const getStaticProps = async () => {
  return {
    props: {
      builderDataContent: await builder.get('site-settings', /* other options like queries and targeting */).promise()
    }
  }
}

export default function MyPage({ builderDataContent }) {
  return <BuilderContent content={builderDataContent}>{data =>
    <ThemeProvider theme={data.theme}>
      {/* ... more content ... */}
    </ThemeProvider>
  </BuilderContent>
}

Usage with Page/Section Custom Fields

Page and section models in builder can be extended with custom fields. To enable live editing / previewing on components that uses those custom fields, you can use BuilderContent to pass input data from the model to your components that are outside the rendered content

Example, passing Custom Field input:
<BuilderContent model="landing-page">
  {data => {
    /*use your data here within your custom component*/
    return (
      <>
        <FeaturedImage image={data.featuredImage} />
        <BuilderComponent content={content} model="landing-page" />
      </>
    );
  }}
</BuilderContent>

Passing content manually

This is useful for doing server side rendering, e.g. with Gatsby and Next.js or via loading data from other sources than our default APIs, such as data in your own database saved via webhooks

const content = await builder.get(‘your-data-model’, { ...options });
if (content) {
  /*use your data here*/
  return <BuilderContent model="your-data-model" content={content} >
}

Advanced querying

When using custom models and fields you can do more advanced filtering of your content with queries and targeting

import { BuilderContent, builder } from '@builder.io/react';

builder.setUserAttributes({ isLoggedIn: false })

export default () => <div>
  <BuilderContent
     model="your-data-model"
     options={{ query: { 'data.something.$in': ['value a', 'value b'] } }} />
  <!-- some other content -->
</div>

builder

The React SDK exports the core SDK's builder object, which can be used for setting things like your API key and user attributes

import { builder } from '@builder.io/react';

builder.init(YOUR_KEY);

// Optional custom targeting
builder.setUserAttributes({
  userIsLoggedIn: true,
  whateverKey: 'whatever value',
});

Lite version

NOTE: If you want a zero-dependencies, fast and small Builder SDK for React, we strongly encourage you to try out our Gen 2 React SDK. You can find it here.

This SDK has a lite version where it provides only the bare minimum of components needed to render your Builder content, it won't have any built-in components registered by default, this option should work with custom components. The main difference is that you need to specifically add any built-in components you want to use or they won’t show up. To use the lite package, you change all your imports from @builder/react to @builder/react/lite and then import only the built-in components that you want to use:

// Change all imports from '@builder.io/react' to '@builder.io/react/lite'
import { BuilderComponent } from '@builder.io/react/lite';

// Import only what built-in components you like to use
import '@builder.io/react/dist/lib/src/blocks/Button';
import '@builder.io/react/dist/lib/src/blocks/Columns';

Guide to use API Version v3 to query for content

For using API Version v3, you need to pass apiVersion as "v3" in the init function. For example:

import { builder } from '@builder.io/react';

// First, initialize the SDK with your API key
builder.init('YOUR_API_KEY_GOES_HERE');
// Then, set the API version to v3
builder.apiVersion = 'v3';

Reasons to switch to API Version v3

  • Better, more scalable infra: Query v3 is built on global scale infrastructure to ensure fast response times and high availability
  • Ability to ship more features, faster: Query V3 will allow us to keep shipping the latest features to our customers without breaking fundamental flows. These will be shipped only to Query V3 and not to the older versions of the query API

Coming soon...

  • Better support for localization: Some of the newer features of localization and querying based on it will be better supported in Query V3
  • Support multi-level nested references: Query V3 will allow you to query, resolve, and return content that has nested references of other contents and symbols.

Node v20 + M1 Macs (Apple Silicon) Support

The SDKs rely on isolated-vm, a library to securely execute code on a Node server. There is a compatibility issue for that library when running on Node v20 and M1 Macs. To workaround this issue, you must provide NODE_OPTIONS=--no-node-snapshot to the command that runs your server.

If you do not provide this flag, the SDK will skip using isolated-vm. This will only occur on Apple Silicon machines that are running Node v20.

For more information, see this issue.

changelog

@builder.io/react

8.2.3

Patch Changes

  • 7adc4f6: Fix: Corrected the implementaion of http requests with GET method
  • 25895a2: Fix: Improved implementation of making Content http-requests with GET method

8.2.2

Patch Changes

  • 31a0d0e: feat: add nonce support for Content Security Policy

8.2.1

Patch Changes

  • 7a0d981: fix: Form submission should use the radio button value rather than name

8.2.0

Minor Changes

  • 3f84ee5: Feature: Added support for POST requests in Content HTTP Requests

8.1.2

Patch Changes

8.1.1

Patch Changes

  • 59cf58a: Add loading=lazy to RawImg component for better perf
  • Updated dependencies [a6eee0e]

8.1.0

Minor Changes

  • e060d32: Add srcset to raw Img component, use intersection observers for Video component

Patch Changes

8.0.13

Patch Changes

8.0.12

Patch Changes

  • ff56386: Fix: correctly set default value for omit field as meta.componentsUsed in Content API calls and preserve empty string
  • Updated dependencies [ff56386]

8.0.11

Patch Changes

  • 93999c0: Fix: centering items inside columns when columns has a fixed height

8.0.10

Patch Changes

  • 372746e: Feat: add title option for images

8.0.9

Patch Changes

  • 3c77cc7: chore: send apiKey to Visual Editor to improve editing experience.

8.0.8

Patch Changes

  • abe5cba: Fix: hydration mismatch error and reactivity of Personalization Containers when userAttributes cookie value is updated.

8.0.7

Patch Changes

  • 58fb07e: Fix: ability to set builder.canTrack before calling builder.init()
  • Updated dependencies [58fb07e]

8.0.6

Patch Changes

  • 2cf49b4: Fix: Removed z-index from video component as its hiding the child elements
  • b1ad88c: feat: Add support for "xsmall" breakpoint size in content entries.
  • Updated dependencies [b1ad88c]

8.0.5

Patch Changes

  • 37c9341: fix: add builder block id only if its present

8.0.4

Patch Changes

  • b0aeaaa: Fix: Dynamic symbols not rendering properly in Visual Editor.

8.0.3

Patch Changes

  • 306f8d5: Fix: add missing folded and keysHelperText types to custom component Input
  • 306f8d5: Types: add firstPublished to BuilderContent
  • Updated dependencies [306f8d5]
  • Updated dependencies [306f8d5]

8.0.2

Patch Changes

  • c822422: Fix: symbols will now show published content instead of preview/autosave content while editing a page
  • Updated dependencies [c822422]

8.0.1

Patch Changes

  • 94fdaee: Fix: clearing image from content input not reflecting in symbols without page refresh.

8.0.0

Major Changes

  • 56f9461: - Adds apiEndpoint prop to builder instance with permitted values being 'content' or 'query'. It dictates which API endpoint is used for fetching Builder content
    • Breaking Change 🧨: Removes apiEndpoint argument from builder.get(), builder.getAll(), and the options prop of <BuilderContent> component. NOTE: this argument was not working as expected.

Patch Changes

  • 06b1124: Fix: remove enrich=true default option passed to the API and instead use includeRefs=true as default
  • a8009ba: Fix: hydration errors in Next v15 while a user is editing
  • 409aec9: Feat: add meta type to custom components
  • 40d572d: Renders Symbol correctly when apiEndpoint is 'content'
  • 23b7594: Feat: extend allowed file types of Image and Video Block
  • ee436bf: Fix: locale prop to automatically resolve localized fields
  • 2fc9fc5: Fix: onChange functions passed to builder inputs can now receive async functions
  • Updated dependencies [06b1124]
  • Updated dependencies [56f9461]
  • Updated dependencies [409aec9]
  • Updated dependencies [40d572d]
  • Updated dependencies [2fc9fc5]

7.0.1

Patch Changes

  • bf8d783: feat: allow symbols to be edited in the context of a parent entry

7.0.0

Major Changes

Patch Changes

6.0.4

Patch Changes

  • b0ab0f5: Add support for dynamic bindings in responsive styles

6.0.3

Patch Changes

  • 9b11521: fix serializing single arg arrow functions that some compilers emit
  • 027a07a: fix: standardize locale handling and pass through locale prop to personalization containers when filtering
  • Updated dependencies [9b11521]
  • Updated dependencies [027a07a]

6.0.2

Patch Changes

  • dda2ba4: Fix: Add trustedHost checks to all remaining event listeners
  • dda2ba4: Fix: Restrict event listening to when isEditing === true
  • Updated dependencies [dda2ba4]

6.0.1

Patch Changes

  • cf33d45: Fix: increase coverage of trustedHost check to all messages.
  • Updated dependencies [cf33d45]

6.0.0

Major Changes

  • f4fffe9: Permanently removes the apiEndpoint prop from builder.get() and builder.getAll() which had options 'content' and 'query'. Content API is now the only possible API endpoint for content fetching.

Patch Changes

5.0.11

Patch Changes

5.0.10

Patch Changes

  • b5dd732: Feature: start sending accurate npm package version information to the Visual Editor
  • Updated dependencies [b5dd732]

5.0.9

Patch Changes

  • 6375b42: Misc: allow react 19 RC releases as a peer dependency (to work with nextjs 15)

5.0.8

Patch Changes

  • 2ae3cc5: Feature: add fetchOptions to options argument within .get(modelName, options) and .getAll(modelName, options), which is passed to the fetch function.
  • 54af3bb: Fix: previewing SDK content within the Studio tab of the Builder Visual Editor.
  • Updated dependencies [2ae3cc5]

5.0.7

Patch Changes

  • 49d0aa3: [Types]: adds a second argument to the onChange argument for custom component Inputs called previousOptions. It contains the options argument in its old state before the current onChange event was triggered.

    Before:

    onChange?:
      | ((options: Map<string, any>) => void | Promise<void>)
      | string;

    After:

      onChange?:
        | ((options: Map<string, any>, previousOptions?: Map<string, any>) => void | Promise<void>)
        | string;
  • Updated dependencies [49d0aa3]

5.0.6

Patch Changes

  • d403fca: Adds apiEndpoint prop to builder.get() and builder.getAll() with options 'content' and 'query'. It dictates which API endpoint is used for the content fetching. Defaults to 'query'
  • Updated dependencies [d403fca]

5.0.5

Patch Changes

  • 0fc86b4: Fix: server-side-rendering of dynamic style bindings

5.0.4

Patch Changes

  • bba43e6: This introduces two new custom events to enhance tracking and analytics for personalization container variants:

    1. builder.variantLoaded: Fired when a variant is loaded.
    2. builder.variantDisplayed: Fired when a variant becomes visible in the viewport.

    Changes

    • Added builder.variantLoaded event dispatch when a variant is loaded.
    • Implemented an Intersection Observer to trigger the builder.variantDisplayed event when the variant enters the viewport.
    • These events are only fired when not in editing or preview mode.

    Example Usage

    These events can be listened to for analytics or other custom behaviors:

    document.addEventListener("builder.variantLoaded", (event) => {
      // This will either be a variant object like { name: 'My Variant', query: [...], startDate: ..., endDate: ... }
      // or the string 'default'
      console.log("Variant loaded:", event.detail.variant);
      // This will be the content object like { name: 'My page', id: '...', ... }
      console.log("Content:", event.detail.content);
      // Perform analytics or other actions
    });
    
    document.addEventListener("builder.variantDisplayed", (event) => {
      console.log("Variant displayed:", event.detail.variant);
      console.log("Content:", event.detail.content);
      // Track impressions or perform other visibility-dependent actions
    });

    Benefits

    • Improved tracking capabilities for personalization variants.
    • Enables more granular analytics for when variants are loaded and actually viewed.
    • Provides hooks for developers to implement custom behaviors based on variant lifecycle events.
  • 8137ce5: Fix: prevent Embed and Custom Code blocks from re-rendering when page orientation changes

5.0.3

Patch Changes

  • 20953a8: Disable localization on dynamic container inputs

5.0.2

Patch Changes

  • 1118b05: Add built-in personalization container to suppoert block level personalization
  • Updated dependencies [1118b05]

5.0.1

Patch Changes

  • 69859d4: serialize functions for registering plugins so you can have showIf on fields as functions
  • Updated dependencies [69859d4]

5.0.0

Major Changes

  • bc1d409: Breaking Change 🧨: userAttributes now is parsed as an object - JSON.stringify(userAttributes) which preserves strings. Users no longer need to manually stringify anything unless they have explicitly included it in custom targeting attributes.

    For example,

    userAttributes: {
      stringWithStrs: ["a", "c"];
    }

    used to work as well as this,

    userAttributes: {
      stringWithStrs: ["'a'", "'c'"];
    }

    but now its not needed to manually stringify strings. This change was needed to preserve data types and strings so previously when we passed,

    userAttributes: {
      stringWithNums: ["1", "2"];
    }

    they were actual string numbers but we failed to parse it because we were not preserving the strings and users had to perform manual stringification hacks like "'1'" to achieve correct result. With this change stringified numbers/bools etc will work out of the box as expected showing less room for randomness.

Patch Changes

  • 1586519: Fix: remove next: { revalidate: 1 } in SDKs fetch
  • Updated dependencies [bc1d409]
  • Updated dependencies [1586519]

4.0.4

Patch Changes

  • b7c00cf: Fix SSR hydration issues with non-hover animated builder blocks
  • Updated dependencies [b7c00cf]

4.0.3

Patch Changes

  • 11e118c: Fix: serialize all functions within registered component info.
  • Updated dependencies [11e118c]

4.0.2

Patch Changes

4.0.1

Patch Changes

  • 4ee499e: Fix: Image block: remove redundant srcset for SVG images

4.0.0

Major Changes

  • d031580: Breaking Change 🧨: Columns block now computes percentage widths correctly, by subtracting gutter space proportionally to each percentage. Previously, it computed the column's widths by subtracting gutter space equally from each column's width. This previous behavior was incorrect, and most strongly felt when the space was a substantially high percentage of the total width of the Columns block.

3.2.12

Patch Changes

  • 1defae7: Refactor: move Embed iframe generation to Visual Editor
  • Updated dependencies [1defae7]

3.2.11

Patch Changes

  • 6187c39: Fix: required option for TextArea and Select blocks
  • 767795c: Fix binding to array property getters and methods in server context

3.2.10

Patch Changes

  • bb4a5fd: Feature: add webp support for Image block file uploads.
  • 1f62b28: Fix: Remove iframely API key from Embed block logic.
  • Updated dependencies [a5b8810]

3.2.9

Patch Changes

  • 945f26e: Adds the highPriority option to the Image block component to ensure eager loading.

3.2.8

Patch Changes

  • 4aaba38: Fix: bump isolated-vm dependency to 5.0.0, adding support for Node v22.
  • Updated dependencies [4aaba38]

3.2.7

Patch Changes

3.2.6

Patch Changes

  • 6dd554f: Update readme with absolute URLs

3.2.5

Patch Changes

  • c32cbd6: Support single jsx node as props.children in withChildren

3.2.4

Patch Changes

  • 3764321: Fix: replace broken default value of Video Block with a working link.

3.2.3

Patch Changes

3.2.2

  • Fix: deviceSize state not getting set properly.

3.2.1

  • Fix: sigfault crash when using SDK in Node v20 + M1 Macs. Skips usage of isolated-vm in those environments.

3.2.0

  • Stricter checking of trusted hosts.

3.1.2

  • Use latest core sdk, to fix secure cookie spacing.

3.1.1

  • Use latest core sdk, to enable passing authToken to getAll on private models.

3.1.0

  • Updated to use latest core sdk (v2.1.0) which now uses true as default for noTraverse option when fetching multiple content entries.

3.0.14

  • Fix: Update core sdk to fix issue with edge runtime in next.js

3.0.13

  • Add support for customComponents prop on BuilderComponent
  • Fix: SSR with text block eval expression

3.0.12

  • Fix: remove dev dependency from dependencies (nx and nx-cloud)

3.0.11

  • Add support for loading symbols from other spaces for the global symbols feature.

3.0.10

3.0.9

  • Fix issue with collection/repeat and returning objects from code bindings in SSR.

3.0.8

  • Replace deprecated package vm2 with isolated-vm.
  • Fix for excessive caching in nextjs 13

3.0.7

  • add back the process keyword with a check for typeof process to fix Hydrogen SSR

3.0.6

  • remove process keyword to fix Hydrogen SSR

3.0.5

  • Fix: Pass locale from parent state to Symbols

3.0.4

  • Chore: update `@builder.io/coreto^2.0.4` to fix import issue

3.0.3

  • Feature: Add support for enrich API flag.
  • Mark includeRefs as deprecated.

3.0.0

  • apiVersion property now defaults to v3.

2.2.0

  • Sets the default apiVersion to v1.

2.1.0

  • Sets the default apiVersion to v3.

In case you feel the need to use our older API Version v1, reach out to us at support@builder.io first. But you can override the default by setting apiVersion explicitly to v1 as follows:

import { builder } from "@builder.io/react";

builder.init("YOUR_BUILDER_PUBLIC_KEY");
builder.apiVersion = "v1";

More details on the Builder API Versions visit this link.

2.0.17

  • Add new apiVersion property to toggle between Builder API versions. Defaults to v1. Possible values: v1 and v3.

You can set the apiVersion using builder.init or builder.apiVersion:

import { builder } from "@builder.io/react";

builder.init("YOUR_BUILDER_PUBLIC_KEY");
builder.apiVersion = "v3";

2.0.16

  • Safe access to node-fetch and process.env.

2.0.15

  • Use correct types for responsiveStyles, fixes remix type checks.

2.0.13

  • Fix hydration errors when a/b testing with react 18
  • Fix overriding state in editor's data tab.

2.0.10

  • Fix issue with Hydrogen SSR.
  • Return null values in bindings when VM2 is not available on the server.

2.0.9

  • Fix for require is not defined bug on client side.

2.0.8

  • Fix SSR issue with hydration
  • Add support for custom breakpoints

2.0.6

  • Add support for threshold and repeat options on ScrollInView animations.

2.0.6

  • added types for override option

2.0.5

  • Add support for locale prop on BuilderComponent to auto-resolve localized inputs.
  • Use the latest core sdk version which addresss an issue with rendering in a middleware (also a shopify hydrogen issue, https://github.com/BuilderIO/builder/issues/610).

2.0.4

  • updates the patching logic to fix bug while where styling updates in the builder editor don’t properly apply (will quickly revert, until you refresh the preview)

2.0.3

  • Fix an issue with previewing drafts of a published data model rendered by BuilderContent.
  • Fix an issue with live editing on a BuilderContent containing a BuilderComponent of the same model.

2.0.3

  • Fix an issue with previewing drafts of a published data model rendered by BuilderContent.
  • Fix an issue with live editing on a BuilderContent containing a BuilderComponent of the same model.

2.0.2

  • Move React/React-dom to peer dependencies to fix installation warnings.
  • Add support for templated variables {{foo}} in Text block.
  • Update vm2 dependency to 3.9.10.

2.0.1

  • Add new hook useIsPreviewing to be used instead of Builder.isEditing and Builder.isPreviewing flags, to fix hydration warnings while editing or previewing.

2.0.0

  • update minimum required react version to >= 16.8

1.1.50

  • update `@builder.io/sdkto1.1.26(adds bugfix tonoTrack` correctly ignoring session cookies)