As Sitecore has started supporting Headless CMS architecture, from my working experience on headless JSS projects, I thought of putting together a series of blogs demonstrating the basics that one has to do in Sitecore Next.js project.
In my first blog, I will explain about creating new component in sitecore and frontend project.
The prerequisite to practically perform these steps is to have project setup.
If project setup is not done, please refer to this informative blog from Martin Miles : Creating a containerized Sitecore Headless StarterKit with the latest Next.js SDK and Headless SXA
Assuming that everything is setup, let’s get started with creating a component:
Create sitecore template
As the first step of creating any component, create a template to define a structure and behavior of item created from that template, create a template in sitecore for required fields. Here I have added 2 fields – Image and Content for example.
Create sitecore component
- Create JSON rendering with appropriate name under folder “/sitecore/layout/Renderings/Project/<Project-Name>”
- Add datasource template and datasource location so that when content editor adds a rendering to any item, defined template will be used to create datasource item and datasource item will be created on specified location.
- Make sure to add newly created component rendering to allowed controls in “Main placeholder” item to leverage the option for content editor to add respective component to item using experience editor.
Create component in Next.js App
XM Cloud Roadmap Guide
XM Cloud is the future of enterprise content management offerings. The new sites, pages, and components tools offer an efficient content author experience that is not available with other CMS systems.
Now that component in Sitecore is created, create component in Next.js App.
- Go to /src/components folder, right click and select “New file”, Create file with .tsx extension.
- Define component with same name as JSON rendering created as Sitecore
- Add fields same as sitecore template as props.
- Render the field props value in Sitecore tags as below.
Add data for component
Open experience editor and add component to placeholder and update data for fields and the data will get rendered as expected
- Once everything is done, publish the content and validate the page.
- I generally use Chrome React developer tool to check what and how data is coming from Layout service
- You can also check same on https://<your site host>/sitecore/api/layout/render/jss?item=/&sc_apikey=<API key>&sc_site=<YOUR SITE NAME>&sc_mode=normal
- API key can be fetched from 2 places:
- scjssconfig.json file under src/rendering folder
- /sitecore/system/Settings/Services/API Keys/<api key item name>