Storyblok
Search Storyblok's Documentation
  1. Dynamic Routing in React

Dynamic Routing in React

Dynamic Routing in React

Set up a catch-all route strategy in your React project to render new stories dynamically.

Setup

Install the react-router package in the terminal.

npm install react-router

Fetch a story dynamically

Modify the App.jsx file to fetch any story within your Space.

src/App.jsx
import { StoryblokComponent, useStoryblok } from '@storyblok/react';
import { useParams } from 'react-router';

export default function App() {
   const params = useParams();
   const slug = params['*']
   const story = useStoryblok(slug || 'home', {
   const story = useStoryblok('home', {
    version: 'draft',
  });

  if (!story?.content) {
    return <div>Loading...</div>;
  }
  return <StoryblokComponent blok={story.content} />;
}

Get the slug from the current route, making an exception for our home story to be /.

Render all stories

Update main.jsx to use React Router.

src/main.jsx
 import { createBrowserRouter, RouterProvider } from 'react-router';
import {createRoot} from 'react-dom/client';
import { StrictMode } from 'react';
import './index.css';
import App from "./App"
import { storyblokInit, apiPlugin } from '@storyblok/react';

import Page from './storyblok/Page';
import Teaser from './storyblok/Teaser';
import Feature from './storyblok/Feature';
import Grid from './storyblok/Grid';

storyblokInit({
  accessToken: import.meta.env.VITE_STORYBLOK_ACCESS_TOKEN,
  use: [apiPlugin],
  components: {
    page: Page,
    teaser: Teaser,
    feature: Feature,
    grid: Grid
  },
  apiOptions: {
    region: 'eu', // "eu" is the default region
  },
});

 const router = createBrowserRouter([
 {
    path: '/*',
    Component: App,
  }
]);

const root = document.getElementById('root');

createRoot(root).render(
  <StrictMode>
    <RouterProvider router={router} />
    <App />
  </StrictMode>
);

With this approach, your project can automatically handle new stories you add to your Space.