Rendering basics
Contents
In this chapter you will look into the basic rendering mechanisms, and add custom rendering to your app.
Dev mode rendering
As you saw when setting up Next.js, each content item automatically maps to a page listing available props. These props are fetched by the Enonic adapter.
By defining custom queries and React components tailored for each content type, you can customize the props passed to the view, and which React template is actually applied.
Task: Get person content
Build your first component, starting with the query for the "Person" content type.
The full name of your content type should now be com.example.tutorial.nextjs:person. If you used a different name when creating the Enonic app, update the .env file in your Next.js app to reflect this. |
-
Add a query - Create the following file in your front-end application:
src/components/queries/getPerson.tsimport { APP_NAME_UNDERSCORED, imageUrlQuery, pageUrlQuery } from '@enonic/nextjs-adapter'; const getPerson = () => ` query { guillotine(scopeKey: $scopeKey, branch: $branch, project: $project) { get(key:$path) { displayName ... on ${APP_NAME_UNDERSCORED}_Person { data { dateofbirth photos { ... on media_Image { ${imageUrlQuery({ scale: 'width(500)' })} attachments { name } } } } } parent { _path ${pageUrlQuery()} } } } }`; export default getPerson;This file defines a GraphQL query,
getPerson, that fetches data from the Enonic API.The query uses the variables scopeKey,branch,projectandpath, which are automatically populated by the Enonic adapter.You may validate the query by copying it to Query Playground. Replace APP_NAME_UNDERSCOREDwithcom_example_tutorial_nextjsand set the query variables, for instance:{"path": "/hmdb/persons/brad-pittless", "project": "intro", "branch": "draft", "scopeKey": "/hmdb"} -
Add the following imports to the component mappings file:
src/components/_mappings.tsimport getPerson from './queries/getPerson'; import {APP_NAME} from '@enonic/nextjs-adapter'; -
Register the query in the same file:
src/components/_mappings.ts// Content type mappings ComponentRegistry.addContentType(`${APP_NAME}:person`, { query: getPerson, view: PropsView }); -
Verify the result - Visit a person item, like http://localhost:3000/persons/morgan-floatman. The view now lists the data props from your query.
Media URLs
The getPerson query requests the image with ${imageUrlQuery({scale: 'width(500)'})}, a Next.XP helper that selects the URL object (path, queryString and the media components) of a scaled version of the image. Its path is server-relative, so the view turns it into an absolute URL pointing at XP’s media API with imageUrl(photo.imageUrl). The base URL comes from ENONIC_MEDIA_CDN and defaults to ENONIC_API, so no XP configuration is needed.
Every Guillotine URL field has such a pair: imageUrlQuery()/imageUrl(), mediaUrlQuery()/mediaUrl(), attachmentUrlQuery()/attachmentUrl() and pageUrlQuery()/pageUrl(). The pageUrl(data, meta) function is the one to use for links between content items: it returns a relative URL prefixed with the current locale, except for the default locale which has no prefix.
Task: Add a person view
With fresh content available, it’s time to make things shine.
-
Add a view - Create the following file in your Next.js application:
src/components/views/Person.tsximport React from 'react'; import { FetchContentResult, I18n, imageUrl, pageUrl } from '@enonic/nextjs-adapter'; import Link from 'next/link'; const Person = (props: FetchContentResult) => { const { displayName, data, parent } = props.data?.get as any; const { photos } = data; const meta = props.meta; return ( <> <div> <h2>{displayName}</h2> { photos.map((photo: any, i: number) => ( <img key={i} src={imageUrl(photo.imageUrl, meta)} title={getTitle(photo, displayName)} alt={getTitle(photo, displayName)} width="500" /> )) } </div> <p><Link href={pageUrl(parent.pageUrl, meta)} data-content-path={parent._path}>{I18n.localize( 'back')}</Link></p> </> ); }; export default Person; function getTitle(photo: any, displayName: string) { return (photo.attachments || [])[0].name || displayName; }This file defines a React view,
Person, that uses the props from the query to render the person. -
Register the Person view - Add the following import to the component mappings:
src/components/_mappings.tsimport Person from './views/Person';Then update the component mapping you created earlier to use the new view:
src/components/_mappings.ts// Content type mappings ComponentRegistry.addContentType(`${APP_NAME}:person`, { query: getPerson, view: Person }); -
Verify the result - The page reloads automatically once the changes have been saved:
The content type mapping applies to every person content item in the site, regardless of its location in the hierarchy. Try looking at some other persons, such as http://localhost:3000/persons/uma-tieoffman.
Task: Add a custom header and footer
A header and a footer make the site more interesting visually, and Next.js layouts are a handy way of adding them.
Next.js layouts wrap every page below them. The starter has a root layout (src/app/layout.tsx), a locale layout and a content layout (src/app/[locale]/[[…contentPath]]/layout.tsx). By modifying the last one, you can inject the same header and footer components into all content pages.
Sample header and footer views are already included in the starter under src/components/views, so all you need to do is put them to work. |
Update src/app/[locale]/[[…contentPath]]/layout.tsx with the following changes:
-
Add these imports:
import Header from '../../../components/views/Header'; import Footer from '../../../components/views/Footer'; -
Replace the return statement - At the bottom of the file, replace the entire return statement:
return ( <LocaleContextProvider locale={resolvedParams.locale}> <StaticContent condition={isEdit}> <main>{children}</main> <DraftModeIndicator label={I18n.localize('draft-mode')}/> </StaticContent> </LocaleContextProvider> )With this:
return ( <LocaleContextProvider locale={resolvedParams.locale}> <StaticContent condition={isEdit}> <Header meta={meta} title={I18n.localize('title')} logoUrl="/images/xp-logo.svg"/> <main>{children}</main> <Footer/> <DraftModeIndicator label={I18n.localize('draft-mode')}/> </StaticContent> </LocaleContextProvider> ) -
Verify the result - Morgan Floatman’s page should now look like this:
The common query
You may have noticed the Common props appearing in the various prop views. These originate from the following statement in the mappings:
...
// Common query
ComponentRegistry.setCommonQuery([commonQuery, commonVariables]);
...
The result of this query is available across all components on the page, and may be useful if you want to fetch data for the page itself or to be used across multiple components. Feel free to adapt it to your requirements.
| If you do not need any common props, remove the common query from the mappings to optimize performance. |
Summary
You’ve added a query and a view for the person content type, registered them in the component mappings, and wrapped all content pages in a header and a footer.
Next, you’ll add preview support to Content Studio.