🚀 Usage
If you are first-time user of the Storyblok, read the Getting Started guide to get a project ready in less than 5 minutes.
Installation
Install @storyblok/react
:
npm install @storyblok/react
// yarn add @storyblok/react
⚠️ This SDK uses the Fetch API under the hood. If your environment doesn't support it, you need to install a polyfill like isomorphic-fetch. More info on storyblok-js-client docs.
From a CDN
Install the file from the CDN:
<script src="https://unpkg.com/@storyblok/react"></script>
Initialization
Register the plugin on your application and add the access token of your Storyblok space. You can also add the apiPlugin
in case that you want to use the Storyblok API Client:
For Spaces created under US
region, you should pass the region like { apiOptions: { region: 'us' } }
. If your space is under EU
, no further configuration is required.
import { storyblokInit, apiPlugin } from "@storyblok/react";
storyblokInit({
accessToken: "YOUR_ACCESS_TOKEN",
apiOptions: {
region: "us",
},
use: [apiPlugin],
components: {
page: Page,
teaser: Teaser,
grid: Grid,
feature: Feature,
},
});
Add all your components to the components object in the storyblokInit
function.
That's it! All the features are enabled for you: the Api Client for interacting with Storyblok CDN API, and Storyblok Bridge for real-time visual editing experience.
You can enable/disable some of these features if you don't need them, so you save some KB. Please read the "Features and API" section
Getting Started
@storyblok/react
does three actions when you initialize it:
- Provides a
getStoryblokApi
object in your app, which is an instance of storyblok-js-client. - Loads Storyblok Bridge for real-time visual updates.
- Provides a
storyblokEditable
function to link editable components to the Storyblok Visual Editor.
1. Fetching Content
Inject getStoryblokApi
:
import { storyblokInit, apiPlugin, getStoryblokApi } from "@storyblok/react";
storyblokInit({
accessToken: "YOUR_ACCESS_TOKEN",
use: [apiPlugin],
components: {
page: Page,
teaser: Teaser,
grid: Grid,
feature: Feature,
},
});
const storyblokApi = getStoryblokApi();
const { data } = await storyblokApi.get("cdn/stories", { version: "draft" });
Note: if you don't use apiPlugin
, you can use your prefered method or function to fetch your data.
2. Listen to Storyblok Visual Editor events
Use useStoryblok
to get the new story every time is triggered a change
event from the Visual Editor. You need to pass the slug
as first param, and apiOptions
as second param to update the new story. bridgeOptions
(third param) is optional param if you want to set the options for bridge by yourself:
import { useStoryblok, StoryblokComponent } from "@storyblok/react";
function App() {
const story = useStoryblok("react", { version: "draft" });
if (!story?.content) {
return <div>Loading...</div>;
}
return <StoryblokComponent blok={story.content} />;
}
export default App;
You can pass Bridge options as a third parameter as well:
useStoryblok(story.id, (story) => (state.story = story), {
resolveRelations: ["Article.author"],
});
3. Link your components to Storyblok Visual Editor
For every component you've defined in your Storyblok space, call the storyblokEditable
function with the blok content:
import { storyblokEditable } from "@storyblok/react";
const Feature = ({ blok }) => {
return (
<div {...storyblokEditable(blok)} key={blok._uid} data-test="feature">
<div>
<div>{blok.name}</div>
<p>{blok.description}</p>
</div>
</div>
);
};
export default Feature;
Where blok
is the actual blok data coming from Storblok's Content Delivery API.
As an example, you can check in our Next.js example demo how we use APIs provided from React SDK to combine with Next.js projects.
import {
useStoryblokState,
getStoryblokApi,
StoryblokComponent,
} from "@storyblok/react";
export default function Home({ story: initialStory }) {
const story = useStoryblokState(initialStory);
if (!story.content) {
return <div>Loading...</div>;
}
return <StoryblokComponent blok={story.content} />;
}
export async function getStaticProps({ preview = false }) {
const storyblokApi = getStoryblokApi();
let { data } = await storyblokApi.get(`cdn/stories/react`, {
version: "draft",
});
return {
props: {
story: data ? data.story : false,
preview,
},
revalidate: 3600,
};
}
If you'd like to have a React.js example demo, you can find it and try it out in your environement from here:
React.js example demo
Features and API
You can choose the features to use when you initialize the plugin. In that way, you can improve Web Performance by optimizing your page load and save some bytes.
Storyblok API
You can use an apiOptions
object. This is passed down to the storyblok-js-client config object:
storyblokInit({
accessToken: "YOUR_ACCESS_TOKEN",
apiOptions: {
cache: { type: "memory" },
},
use: [apiPlugin],
components: {
page: Page,
teaser: Teaser,
grid: Grid,
feature: Feature,
},
});
If you prefer to use your own fetch method, just remove the apiPlugin
and storyblok-js-client
won't be added to your application.
storyblokInit({});
Storyblok Bridge
If you don't use registerStoryblokBridge
, you still have access to the raw window.StoryblokBridge
:
const sbBridge = new window.StoryblokBridge(options);
sbBridge.on(["input", "published", "change"], (event) => {
});
Rendering Rich Text
You can easily render rich text by using the renderRichText
function that comes with @storyblok/react
:
import { renderRichText } from "@storyblok/react";
const renderedRichText = renderRichText(blok.richtext);
You can set a custom Schema and component resolver globally at init time by using the richText
init option:
import { RichTextSchema, storyblokInit } from "@storyblok/react";
import cloneDeep from "clone-deep";
const mySchema = cloneDeep(RichTextSchema);
storyblokInit({
accessToken: "<your-token>",
richText: {
schema: mySchema,
resolver: (component, blok) => {
switch (component) {
case "my-custom-component":
return `<div class="my-component-class">${blok.text}</div>`;
default:
return "Resolver not defined";
}
},
},
});
You can also set a custom Schema and component resolver only once by passing the options as the second parameter to renderRichText
function:
import { renderRichText } from "@storyblok/react";
renderRichText(blok.richTextField, {
schema: mySchema,
resolver: (component, blok) => {
switch (component) {
case "my-custom-component":
return `<div class="my-component-class">${blok.text}</div>`;
break;
default:
return `Component ${component} not found`;
}
},
});
🔗 Related Links
ℹ️ More Resources
Support
Contributing
Please see our contributing guidelines and our code of conduct.
This project use semantic-release for generate new versions by using commit messages and we use the Angular Convention to naming the commits. Check this question about it in semantic-release FAQ.