How to use strapi's components to render dynamic data in remix?

174 Views Asked by At

im building a simple corporate website with a frontpage, about, blog, single blog posts.

If i create components in strapi, i can just render them with remix from the data i get from remix loaders.

I would like to create a teaser component that fetches 3 of the newest blog posts no matter where i put the component inside strapi.

With my current understanding of remix, i can only fetch through loaders if i want to stay with ssr.

Thanks for helping out!!!

my loader function:

export async function getPageBySlug(slug) {
  const token = process.env.STRAPI_API_TOKEN;

  if (!token)
    throw new Error("The Strapi API Token environment variable is not set.");

  const path = `/pages`;
  const options = { headers: { Authorization: `Bearer ${token}` } };

  const urlParamsObject = {
    filters: { slug },
    populate: {
      thumbnail: { fields: ["url"] },
      seo: { populate: "*" },
      sections: { populate: "*" },
    },
  };

  const baseUrl = getStrapiURL();
  const page = await fetchAPI(path, urlParamsObject, options);

  return {
    page: page.data[0],
    baseUrl: baseUrl,
    slug: slug,
  };
}

thats my front page

export default function Home() {
const { page } = useLoaderData();
const { attributes } = page || {}; // Destructure attributes if page exists

    if (attributes) {
        const { sections } = attributes;
        return (
            <main>
                {sections.map((section, index) => sectionRenderer(section, index))}
            </main>
        );
    } else {
        return <Error />;
    }

and here is the sectionRenderer:

import Hero from "../components/Hero";
import Teaser from "../components/Teaser";

export function sectionRenderer(section, index) {
    switch (section.\__component) {
        case "sections.hero":
            return \<Hero key={index} data={section} /\>;
        case "sections.teaser":
            return \<Teaser key={index} data={section} /\>;
        default:
            return null;
    }
}
1

There are 1 best solutions below

0
Corey Byrum On

I would like to create a teaser component that fetches 3 of the newest blog posts no matter where i put the component inside strapi.

import { useLoaderData } from "@remix-run/react"

export async function loader() {
    return json(await fakeDb.blogPosts.findAll())
    // sort and return
}

export default function BlogPosts() {
    const posts = useLoaderData<typeof loader>()
    // ...
    return posts.map(post => <Post {...post} ../>
}

Within your componentRender/sectionRenderer/renderer component render hierarchy (align with Strapi) place on page