How to connect content data to front-end components
Last updated
Last updated
Rangle.io
Once you have a component library, the next step of building a headless platform is connecting your content models to your front-end components. Your website will probably have templated and non-templated pages.
The process for building a templated page is relatively straightforward. Dynamically building a non-templated page is more complex as page content and layout will vary, depending on what the content author has selected.
Authors will see pre-defined content fields when composing a templated page. They won't be able to reorder components or otherwise modify the layout of the page.
Let's take a blog post as an example. Users can input the title, date, summary, and body of the blog post.
Sanity would return a JSON object that looks like this:
To generate the blog post as a page, you need to map the JSON fields to the right components and map the keys from the JSON file to the appropriate place in the page template.
The result is a static HTML file of our blog post page.
Authors can choose from a selection of components and page modules when composing a non-templated page. They can add and move content around and change the page layout.
To build a non-templated page, we need to dynamically connect the JSON data from the CMS to our front-end components. The magic is in a single function we call buildComponent
.
You'll likely see different implementations across various frameworks and starter repos. We'll walk through our general approach by explaining how we can do this in Next.js.
buildComponent
in Next.jsLet's look at this example JSON containing CMS content data:
Import all the components you need to dynamically build a given page. These should be your CMS module components from your component library.
Map the content models in your CMS to the front-end components in your component library.
Name your content models and components so their field names and prop names match, respectively.
This is critical for matching content data from your CMS to the appropriate components in your component library, to dynamically generate a non-templated page.
If the name of a content model in your JSON doesn't match the name of its corresponding component, you'll need to explicitly define a map object to pair the names of your content model and component.
Pass the component names and props from the CMS to generate the dynamic component.
When we put everything together, buildComponent.jsx
looks like this:
You can now use this function whenever you need to dynamically create components on a page template.