### Development Setup Source: https://github.com/datocms/react-datocms/blob/master/README.md Set up and start the development environment for the examples directory. ```bash cd examples npm setup npm run start ``` -------------------------------- ### Install react-datocms Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Install the react-datocms package using npm. ```bash npm install --save react-datocms ``` -------------------------------- ### Install react-datocms and Mux Player Source: https://github.com/datocms/react-datocms/blob/master/docs/video-player.md Install the react-datocms package and its peer dependency @mux/mux-player-react. Ensure @mux/mux-player-react is added to your project. ```bash npm install --save react-datocms @mux/mux-player-react ``` -------------------------------- ### Install react-datocms and CMA Client Source: https://github.com/datocms/react-datocms/blob/master/docs/site-search.md Install the necessary packages for the useSiteSearch hook and DatoCMS CMA Client. Ensure you have the CMA Client for browser-based API requests. ```bash npm install --save react-datocms @datocms/cma-client-browser ``` -------------------------------- ### Example: Custom Editing Toolbar Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Demonstrates how to build a custom editing toolbar using the `useContentLink` hook. This allows for tailored user interfaces for content editing. ```jsx import { useContentLink } from '@datocms/react-datocms'; function CustomToolbar() { const { isEditingEnabled, startEditing, stopEditing } = useContentLink(); return ( ); } ``` -------------------------------- ### Basic Setup: Add ContentLink Component Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Integrate the ContentLink component into your React application to enable visual editing. Ensure you have fetched content with stega encoding. ```jsx import { ContentLink } from '@datocms/react-datocms'; function MyApp() { // ... fetch your content ... const content = { // ... your content data ... }; return ( <> {/* ... other components ... */} {/* ... other components ... */} ); } ``` -------------------------------- ### Complete Site Search Example with Pagination Source: https://github.com/datocms/react-datocms/blob/master/docs/site-search.md Use this snippet to implement a client-side site search interface. It requires the @datocms/cma-client-browser, react-datocms, and react-paginate packages. Ensure you replace 'YOUR_API_TOKEN' with your actual API token. ```jsx import { buildClient } from '@datocms/cma-client-browser'; import ReactPaginate from 'react-paginate'; import { useSiteSearch } from 'react-datocms'; import { useState } from 'react'; const client = buildClient({ apiToken: 'YOUR_API_TOKEN' }); function App() { const [query, setQuery] = useState(''); const { state, error, data } = useSiteSearch({ client, initialState: { locale: 'en' }, highlightMatch: (text, key, context) => context === 'title' ? ( {text} ) : ( {text} ), searchIndexId: '7497', resultsPerPage: 10, }); return (
{ e.preventDefault(); state.setQuery(query); }} > setQuery(e.target.value)} />
{!data && !error &&

Loading...

} {error &&

Error! {error}

} {data && ( <> {data.pageResults.map((result) => (
{result.title}
{result.bodyExcerpt}
{result.url}
))}

Total results: {data.totalResults}

{ state.setPage(selected); }} activeClassName="active" renderOnZeroPageCount={() => null} /> )}
); } ``` -------------------------------- ### Example: Conditional Editing in Different Environments Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Showcases how to conditionally enable or disable editing based on the environment using the `useContentLink` hook. This is useful for preventing editing in production. ```jsx import { useContentLink } from '@datocms/react-datocms'; function ConditionalEditing() { const { isEditingEnabled } = useContentLink(); if (process.env.NODE_ENV === 'production' && isEditingEnabled) { // Do not allow editing in production return null; } return (
{isEditingEnabled ? 'Editing is active.' : 'Editing is inactive.'}
); } ``` -------------------------------- ### GraphQL Query for SEO and Favicon Tags Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Example GraphQL query to fetch SEO meta tags from a page and favicon meta tags from the site. ```graphql query { page: homepage { title seo: _seoMetaTags { attributes content tag } } site: _site { favicon: faviconMetaTags { attributes content tag } } } ``` -------------------------------- ### Custom Editing Toolbar with useContentLink Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Implement a custom editing toolbar using the useContentLink hook. This example shows how to toggle editing modes and highlight editable areas. ```jsx import { useContentLink } from 'react-datocms'; import { useState } from 'react'; function EditingToolbar() { const { enableClickToEdit, disableClickToEdit, isClickToEditEnabled, flashAll } = useContentLink({ onNavigateTo: (path) => window.location.href = path, }); const [isEditing, setIsEditing] = useState(false); const toggleEditing = () => { if (isEditing) { disableClickToEdit(); } else { enableClickToEdit({ scrollToNearestTarget: true }); } setIsEditing(!isEditing); }; return (
); } ``` -------------------------------- ### Next.js App Router Integration Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Example of setting up the ContentLink component within a Next.js App Router environment. This ensures visual editing works correctly with server components. ```jsx import { ContentLink } from '@datocms/react-datocms'; export default function MyPage({ content }) { return ( <> {/* ... other components ... */} {/* ... other components ... */} ); } ``` -------------------------------- ### Render Favicon Meta Tags in Remix Root Component Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Example of rendering favicon meta tags within the root component of a Remix application using renderMetaTags. ```jsx import { renderMetaTags } from 'react-datocms'; export const loader = () => { return request({ query: ` { site: _site { favicon: faviconMetaTags(variants: [icon, msApplication, appleTouchIcon]) { ...metaTagsFragment } } } ${metaTagsFragment} `, }); }; export default function App() { const { site } = useLoaderData(); return ( {renderMetaTags(site.favicon)} ... ); } ``` -------------------------------- ### Conditional Editing Based on Environment Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Conditionally enable Visual Editing based on environment variables. This example uses NEXT_PUBLIC_DRAFT_MODE to control the hook's enabled state and trigger editing. ```jsx import { useContentLink } from 'react-datocms'; function ConditionalEditing() { const isDraftMode = process.env.NEXT_PUBLIC_DRAFT_MODE === 'true'; const { enableClickToEdit } = useContentLink({ enabled: isDraftMode, onNavigateTo: (path) => router.push(path), }); // Only enable in draft mode useEffect(() => { if (isDraftMode) { enableClickToEdit(); } }, [isDraftMode, enableClickToEdit]); return null; } ``` -------------------------------- ### Handling Multiple Stega Strings Without Groups Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md When multiple stega-encoded strings are siblings without group wrappers, they can collide. This example shows the potential collision and the recommended fix using spans. ```tsx

{/* Both product.name and product.tagline contain stega encoding */} {product.name} {product.tagline}

``` ```tsx

{product.name} {product.tagline}

``` -------------------------------- ### Custom Rendering for Structured Text Nodes Source: https://github.com/datocms/react-datocms/blob/master/docs/structured-text.md Pass custom renderers for inline records, record links, and blocks as optional parameters to the StructuredText component. This example shows how to handle `TeamMemberRecord`, `CtaRecord`, and `MentionRecord` types. ```javascript import React from 'react'; import { StructuredText, Image } from 'react-datocms'; const Page = ({ data }) => { // data.blogPost.content -> // { // value: { // schema: "dast", // document: { // type: "root", // children: [ // { // type: "heading", // level: 1, // children: [ // { type: "span", value: "Welcome onboard " }, // { type: "inlineItem", item: "324321" }, // ], // }, // { // type: "paragraph", // children: [ // { type: "span", value: "So happy to have " }, // { // type: "itemLink", // item: "324321", // children: [ // { // type: "span", // marks: ["strong"], // value: "this awesome humang being", // }, // ] // }, // { type: "span", value: " in our team! We call him " }, // { type: "inlineBlock", item: "1984560" } // ] // }, // { type: "block", item: "1984559" } // ], // }, // }, // links: [ // { // id: "324321", // __typename: "TeamMemberRecord", // firstName: "Mark", // slug: "mark-smith", // }, // ], // blocks: [ // { // id: "1984559", // __typename: "CtaRecord", // title: "Call to action", // url: "https://google.com" // }, // ], // inlineBlocks: [ // { // id: "1984560", // __typename: "MentionRecord", // username: "steffoz", // }, // ], // } return (

{data.blogPost.title}

{ switch (record.__typename) { case 'TeamMemberRecord': return {record.firstName}; default: return null; } }} renderLinkToRecord={({ record, children, transformedMeta }) => { switch (record.__typename) { case 'TeamMemberRecord': return ( {children} ); default: return null; } }} renderBlock={({ record }) => { switch (record.__typename) { case 'CtaRecord': return ( {record.title} ); default: return null; } }} renderInlineBlock={({ record }) => { switch (record.__typename) { case 'MentionRecord': return ( @{record.username} ); default: return null; } }} /> {/* Final result:

Welcome onboard Mark

So happy to have this awesome humang being in our team! We call him @steffoz

Our team at work */}
); }; const query = gql` query { blogPost { title content { value links { ... on RecordInterface { id __typename } ... on TeamMemberRecord { firstName slug } } blocks { ... on RecordInterface { id __typename } ... on CtaRecord { title url } } inlineBlocks { ... on RecordInterface { id __typename } ... on MentionRecord { username } } } } } `; export default withQuery(query)(Page); ``` -------------------------------- ### Placing Boundary Directly on Stega Text Element Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md When the boundary attribute is placed directly on the element containing the stega text, that element itself becomes the clickable target for editing, as the starting element and the boundary element are the same. ```tsx
{/* page.title contains stega encoding → resolves to URL A */}

{page.title}

{/* page.author contains stega encoding → resolves to URL B */} {page.author}
``` -------------------------------- ### Initialization Options Source: https://github.com/datocms/react-datocms/blob/master/docs/live-real-time-updates.md Configure the real-time subscription by providing these options during initialization. ```APIDOC ## Initialization Options This section details the available properties for configuring real-time subscriptions. ### Properties - **enabled** (boolean) - Optional - Whether the subscription should be performed. Defaults to `true`. - **query** (string | TypedDocumentNode) - Required - The GraphQL query to subscribe. - **token** (string) - Required - DatoCMS API token to use. - **variables** (Object) - Optional - GraphQL variables for the query. - **includeDrafts** (boolean) - Optional - If true, draft records will be returned. - **excludeInvalid** (boolean) - Optional - If true, invalid records will be filtered out. - **environment** (string) - Optional - The name of the DatoCMS environment where to perform the query (defaults to the primary environment). - **contentLink** ('vercel-1' or undefined) - Optional - If true, embed metadata that enables Content Link. - **baseEditingUrl** (string) - Optional - The base URL of the DatoCMS project. - **cacheTags** (boolean) - Optional - If true, receive the Cache Tags associated with the query. - **initialData** (Object) - Optional - The initial data to use on the first render. - **reconnectionPeriod** (number) - Optional - In case of network errors, the period (in ms) to wait to reconnect. Defaults to `1000`. - **fetcher** (fetch-like function) - Optional - The fetch function to use to perform the registration query. Defaults to `window.fetch`. - **eventSourceClass** (EventSource-like class) - Optional - The EventSource class to use to open up the SSE connection. Defaults to `window.EventSource`. - **baseUrl** (string) - Optional - The base URL to use to perform the query. Defaults to `https://graphql-listen.datocms.com`. ``` -------------------------------- ### Use Query Subscription for Live Updates Source: https://github.com/datocms/react-datocms/blob/master/docs/live-real-time-updates.md This snippet demonstrates how to use the `useQuerySubscription` hook to fetch data and receive live updates. It shows how to handle connection status, errors, and render the fetched data. Ensure you replace 'YOUR_API_TOKEN' with your actual DatoCMS API token. ```javascript import React from 'react'; import { useQuerySubscription } from 'react-datocms'; const App: React.FC = () => { const { status, error, data } = useQuerySubscription({ enabled: true, query: " query AppQuery($first: IntType) { allBlogPosts { slug title } }", variables: { first: 10 }, token: 'YOUR_API_TOKEN', }); const statusMessage = { connecting: 'Connecting to DatoCMS...', connected: 'Connected to DatoCMS, receiving live updates!', closed: 'Connection closed', }; return (

Connection status: {statusMessage[status]}

{error && (

Error: {error.code}

{error.message}
{error.response && (
{JSON.stringify(error.response, null, 2)}
)}
)} {data && (
    {data.allBlogPosts.map((blogPost) => (
  • {blogPost.title}
  • ))}
)}
); }; ``` -------------------------------- ### Basic VideoPlayer Usage with GraphQL Query Source: https://github.com/datocms/react-datocms/blob/master/docs/video-player.md Import and use the VideoPlayer component with data fetched via a GraphQL query. The component automatically uses the provided video data for optimal playback, including placeholders and lazy loading. ```javascript import React from 'react'; import { VideoPlayer } from 'react-datocms'; const Page = ({ data }) => (

{data.blogPost.title}

); const query = gql` query { blogPost { title cover { video { # required: this field identifies the video to be played muxPlaybackId # all the other fields are not required but: # if provided, title is displayed in the upper left corner of the video title # if provided, width and height are used to define the aspect ratio of the # player, so to avoid layout jumps during the rendering. width height # if provided, it shows a blurred placeholder for the video blurUpThumb # if provided, it enables DatoCMS Content Link for click-to-edit overlays alt # you can include more data here: they will be ignored by the component } } } } `; export default withQuery(query)(Page); ``` -------------------------------- ### Sync Navigation with Web Previews Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Ensure navigation in your preview syncs with the DatoCMS editor by providing both 'onNavigateTo' and 'currentPath' props to ContentLink. ```jsx router.push(path)} currentPath={pathname} /> ``` -------------------------------- ### useContentLink Hook API Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Demonstrates the available properties and options for the useContentLink hook. Use this to understand the hook's capabilities and how to configure it. ```typescript import { useContentLink } from 'react-datocms'; const { controller, // The underlying controller instance enableClickToEdit, // Enable click-to-edit overlays disableClickToEdit, // Disable click-to-edit overlays isClickToEditEnabled, // Check if click-to-edit is enabled flashAll, // Highlight all editable elements setCurrentPath, // Notify Web Previews plugin of current path } = useContentLink({ // enabled can be: // - true (default): Enable with default settings (stega encoding preserved) // - false: Disable the controller // - { stripStega: true }: Enable and strip stega encoding for clean DOM enabled: true, onNavigateTo: (path) => { /* handle navigation */ }, root: elementRef, }); ``` -------------------------------- ### Import Stega Utilities Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Import the necessary utility functions from the react-datocms/stega subpath. These functions can be used in both server and client components. ```typescript import { stripStega, decodeStega, revealStega } from 'react-datocms/stega'; ``` -------------------------------- ### Fetch Content with Stega Encoding Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Fetch content from DatoCMS with stega encoding enabled by setting `contentLink: 'v1'` and providing `baseEditingUrl`. This embeds invisible metadata for Visual Editing. ```javascript import { executeQuery } from '@datocms/cda-client'; const query = " query { page { title content } } "; const result = await executeQuery(query, { token: 'YOUR_API_TOKEN', environment: 'main', // Enable stega encoding contentLink: 'v1', // Set your site's base URL for editing links baseEditingUrl: 'https://your-project.admin.datocms.com', }); ``` -------------------------------- ### Initialize useSiteSearch Hook Source: https://github.com/datocms/react-datocms/blob/master/docs/site-search.md Import and use the useSiteSearch hook within your React components. Pass a configured DatoCMS CMA Client instance and specify the search index ID. Optional parameters include fuzzy search, locale, highlight matching text, and results per page. ```javascript import { useSiteSearch } from 'react-datocms'; import { buildClient } from '@datocms/cma-client-browser'; const client = buildClient({ apiToken: 'YOUR_API_TOKEN' }); const { state, error, data } = useSiteSearch({ client, searchIndexId: '7497', // optional: by default fuzzy-search is not active fuzzySearch: true, // optional: you can omit it you only have one locale, or you want to find results in every locale initialState: { locale: 'en' }, // optional: to configure how to present the part of page title/content that matches the query highlightMatch: (text, key, context) => context === 'title' ? ( {text} ) : ( {text} ), // optional: defaults to 8 search results per page resultsPerPage: 10, }); ``` -------------------------------- ### Configure Click-to-Edit Options Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Customize click-to-edit behavior with an options object. Use `scrollToNearestTarget` to automatically scroll to visible editable elements, or `hoverOnly` to enable only on non-touch devices. ```jsx // Scroll to nearest editable element if none is visible ``` ```jsx // Only enable on devices with hover capability (non-touch) ``` ```jsx // Combine both options ``` -------------------------------- ### Render Meta Tags to String for Server-Side Use Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Use renderMetaTagsToString to generate an HTML string of meta and link tags for server-side rendering. ```javascript import { renderMetaTagsToString } from 'react-datocms'; const someMoreComplexHtml = ` ${renderMetaTagsToString([...data.page.seo, ...data.site.favicon])} `; ``` -------------------------------- ### `` Component Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md The `` component renders responsive images. It takes a `data` prop containing image information from a DatoCMS GraphQL query and allows customization through various other props. ```APIDOC ## `` Component ### Description Renders responsive images fetched from DatoCMS. ### Props #### `data` (ResponsiveImage object) - Required The actual response you get from a DatoCMS `responsiveImage` GraphQL query. #### `pictureClassName` (string) - Optional Additional className for the root `` tag. #### `pictureStyle` (CSS properties) - Optional Additional CSS rules to add to the root `` tag. #### `imgClassName` (string) - Optional Additional className for the `` tag. #### `imgStyle` (CSS properties) - Optional Additional CSS rules to add to the `` tag. #### `priority` (Boolean) - Optional Disables lazy loading, and sets the image [fetchPriority](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority) to "high". Defaults to `false`. #### `sizes` (string) - Optional The HTML5 [`sizes`](https://web.dev/learn/design/responsive-images/#sizes) attribute for the image (will be used `data.sizes` as a fallback). Defaults to `undefined`. #### `usePlaceholder` (Boolean) - Optional Whether the image should use a blurred image placeholder. Defaults to `true`. #### `srcSetCandidates` (Array) - Optional If `data` does not contain `srcSet`, the candidates for the `srcset` attribute of the image will be auto-generated based on these width multipliers. Defaults to `[0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4]`. #### `referrerPolicy` (string) - Optional Defines which referrer is sent when fetching the image. Defaults to `no-referrer-when-downgrade` to give more useful stats in DatoCMS Project Usages. ``` -------------------------------- ### Image Component Props Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md This section details the various props available for the Image component, allowing for customization of image loading, placeholder behavior, responsive image generation, and styling. ```APIDOC ## Image Component Props ### Description This documentation outlines the props for the Image component, which controls how images are displayed and loaded within a React application using the react-datocms library. ### Props #### onLoad - **Type**: `() => void` - **Required**: No - **Description**: Function triggered when the image has finished loading. - **Default**: `undefined` #### usePlaceholder - **Type**: `Boolean` - **Required**: No - **Description**: Whether the component should use a blurred image placeholder. - **Default**: `true` #### srcSetCandidates - **Type**: `Array` - **Required**: No - **Description**: If `data` does not contain `srcSet`, the candidates for the `srcset` attribute of the image will be auto-generated based on these width multipliers. - **Default**: `[0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4]` #### className - **Type**: `string` - **Required**: No - **Description**: Additional CSS className for root node. - **Default**: `null` #### style - **Type**: `CSS properties` - **Required**: No - **Description**: Additional CSS rules to add to the root node. - **Default**: `null` #### pictureClassName - **Type**: `string` - **Required**: No - **Description**: Additional CSS class for the inner `` tag. - **Default**: `null` #### pictureStyle - **Type**: `CSS properties` - **Required**: No - **Description**: Additional CSS rules to add to the inner `` tag. - **Default**: `null` #### imgClassName - **Type**: `string` - **Required**: No - **Description**: Additional CSS class for the image inside the `` tag. - **Default**: `null` #### imgStyle - **Type**: `CSS properties` - **Required**: No - **Description**: Additional CSS rules to add to the image inside the `` tag. - **Default**: `null` ``` -------------------------------- ### Use useQuerySubscription Hook Source: https://github.com/datocms/react-datocms/blob/master/docs/live-real-time-updates.md Import and use the `useQuerySubscription` hook within your React components to manage real-time data. It returns the query result, error object, and connection status. ```javascript const { data: QueryResult | undefined, error: ChannelErrorData | null, status: ConnectionStatus, } = useQuerySubscription(options: Options); ``` -------------------------------- ### React Component with Image and RSCImage Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md Demonstrates using RSCImage for native lazy loading and Image for custom IntersectionObserver-based lazy loading within a React component. Ensure you have the necessary data structure for blog post and cover images. ```jsx import React from 'react'; import { Image, RSCImage } from 'react-datocms'; const Page = ({ data }) => (

{data.blogPost.title}

{/* uses native loading="lazy" */} {/* custom lazy-loading via IntersectionObserver */}
); const query = gql` query { blogPost { title cover { responsiveImage( imgixParams: { fit: crop, w: 300, h: 300, auto: format } ) { # always required src srcSet width height # not required, but strongly suggested! alt title # blur-up placeholder, JPEG format, base64-encoded, or... base64 # background color placeholder bgColor # you can omit `sizes` if you explicitly pass the `sizes` prop to the image component sizes } } } } `; export default withQuery(query)(Page); ``` -------------------------------- ### Generate Next.js Metadata with toNextMetadata() Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md This function generates a `Metadata` object compatible with Next.js's `generateMetadata` export. It requires fetching content and passing the SEO meta tags to the function. ```javascript export async function generateMetadata(): Promise { const { homepage } = await getHomepageContent() return toNextMetadata(homepage?._seoMetaTags || []) } ``` -------------------------------- ### React Router Integration Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Demonstrates how to integrate the ContentLink component when using React Router for navigation. This ensures click-to-edit functionality works across different routes. ```jsx import { ContentLink } from '@datocms/react-datocms'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; function App() { // ... fetch your content ... const content = { // ... your content data ... }; return ( {/* ... your routes ... */} ); } ``` -------------------------------- ### Component Props Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md The `` component accepts several props to control how images are displayed and loaded. These props allow for customization of layout, transitions, and loading triggers. ```APIDOC ## `` Component Props ### Description The `` component is used to render responsive images fetched from DatoCMS. It provides various props to control its behavior and appearance. ### Props #### `data` - **type**: `ResponsiveImage` object - **required**: Yes - **description**: The actual response object obtained from a DatoCMS `responsiveImage` GraphQL query. #### `layout` - **type**: 'intrinsic' | 'fixed' | 'responsive' | 'fill' - **required**: No - **description**: Determines the layout behavior of the image as the viewport size changes. - **default**: "intrinsic" #### `fadeInDuration` - **type**: integer - **required**: No - **description**: Specifies the duration (in milliseconds) for the fade-in transition effect when the image loads. - **default**: 500 #### `intersectionThreshold` - **type**: float - **required**: No - **description**: Sets the visibility percentage of the placeholder at which the image loading should be triggered. A value of 0 means loading starts as soon as any part of the placeholder is visible, while 1.0 means the entire placeholder must be visible. - **default**: 0 #### `intersectionMargin` - **type**: string - **required**: No - **description**: Defines a margin around the placeholder, similar to CSS `margin`. Values can be percentages and are used to expand or shrink the placeholder's bounding box before intersection calculations. - **default**: "0px 0px 0px 0px" #### `priority` - **type**: Boolean - **required**: No - **description**: When true, disables lazy loading and sets the image `fetchPriority` to "high". - **default**: false #### `sizes` - **type**: string - **required**: No - **description**: The HTML5 `sizes` attribute for the image. Falls back to `data.sizes` if not provided. - **default**: undefined ``` -------------------------------- ### GraphQL Query for Product Data Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md This GraphQL query retrieves product information, including the `_editingUrl` field, which is useful for manually marking elements as editable. ```graphql query { product { id price isActive _editingUrl } } ``` -------------------------------- ### Render Meta Tags in React with Helmet Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Use renderMetaTags to generate React elements for meta and link tags, compatible with react-helmet. ```javascript import React from 'react'; import { renderMetaTags } from 'react-datocms'; import { Helmet } from 'react-helmet'; function Page({ data }) { return (
{renderMetaTags([...data.page.seo, ...data.site.favicon])}
); } ``` -------------------------------- ### Nested Groups for Clickable Regions Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Demonstrates how nested `data-datocms-content-link-group` attributes create independent clickable regions. The innermost group takes precedence for its content. ```tsx
{/* page.title contains stega encoding → resolves to URL A */}

{page.title}

{/* page.subtitle contains stega encoding → resolves to URL B */}

{page.subtitle}

``` -------------------------------- ### Basic StructuredText Usage Source: https://github.com/datocms/react-datocms/blob/master/docs/structured-text.md Render a DatoCMS Structured Text field value using the StructuredText component. Ensure the content prop is correctly formatted with a DAST schema. ```javascript import React from 'react'; import { StructuredText } from 'react-datocms'; const Page = ({ data }) => { // data.blogPost.content = { // value: { // schema: "dast", // document: { // type: "root", // children: [ // { // type: "heading", // level: 1, // children: [ // { // type: "span", // value: "Hello ", // }, // { // type: "span", // marks: ["strong"], // value: "world!", // }, // ], // }, // ], // }, // }, // } return (

{data.blogPost.title}

{/* ->

Hello world!

*/}
); }; const query = gql` query { blogPost { title content { value } } } `; export default withQuery(query)(Page); ``` -------------------------------- ### Trigger Flash-All Highlighting Programmatically Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use the useContentLink hook to programmatically trigger the flash-all feature, which highlights all editable elements on the page. Pass `true` to also scroll to the nearest editable element. ```jsx import { useContentLink } from 'react-datocms'; function DebugButton() { const { flashAll } = useContentLink(); return ( ); } ``` -------------------------------- ### Use useVideoPlayer Hook with DatoCMS Data Source: https://github.com/datocms/react-datocms/blob/master/docs/video-player.md Use the `useVideoPlayer` hook to transform DatoCMS video data into props compatible with the MuxPlayer component. This is useful for custom player implementations. ```javascript import { useVideoPlayer } from 'react-datocms'; const data = { muxPlaybackId: 'ip028MAXF026dU900bKiyNDttjonw7A1dFY', title: 'Title', width: 1080, height: 1920, blurUpThumb: 'data:image/bmp;base64,Qk0eAAAAAAAAABoAAAAMAAAAAQABAAEAGAAAAP8A', }; // `props` is the following object: // // { // playbackId: 'ip028MAXF026dU900bKiyNDttjonw7A1dFY', // title: 'Title', // style: { // aspectRatio: '1080 / 1920', // }, // placeholder: // 'data:image/bmp;base64,Qk0eAAAAAAAAABoAAAAMAAAAAQABAAEAGAAAAP8A', // } const props = useVideoPlayer({ data }); ``` -------------------------------- ### Convert Meta Tags for Remix v1 Meta Function Source: https://github.com/datocms/react-datocms/blob/master/docs/meta-tags.md Utilize toRemixV1Meta to convert DatoCMS meta tags into MetaDescriptor objects for Remix's meta export. ```javascript import type { MetaFunction } from 'remix'; import { toRemixV1Meta } from 'react-datocms'; export const meta: MetaFunction = ({ data: { post } }) => { return toRemixV1Meta(post.seo); }; ``` -------------------------------- ### Image Component with Layout Fill Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md Use layout="fill" to make the image stretch to fit its parent element. This is often paired with objectFit and objectPosition. Ensure the parent has position: relative. ```jsx
``` -------------------------------- ### Incorrect Fetcher Definition (Infinite Loop Risk) Source: https://github.com/datocms/react-datocms/blob/master/docs/live-real-time-updates.md Avoid defining the `fetcher` function inline within the `useQuerySubscription` options. This creates a new function on each render, which can trigger an infinite re-render loop. Use a stable `const` definition outside the component instead. ```javascript export default function Home() { const { status, error, data } = useQuerySubscription({ fetcher: (baseUrl, { headers, method, body }) => { return fetch(baseUrl, { headers: { ...headers, 'X-Custom-Header': "that's needed for some reason", }, method, body, }); }, // Other options here }); return ... } ``` -------------------------------- ### Enable Stega Encoding for API Calls Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Verify that stega encoding is enabled in your API calls by including the 'contentLink' and 'baseEditingUrl' options. ```js const result = await executeQuery(query, { token: 'YOUR_API_TOKEN', contentLink: 'v1', baseEditingUrl: 'https://your-project.admin.datocms.com', }); ``` -------------------------------- ### Strip Stega Encoding Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use the 'stripStega' prop on ContentLink to remove invisible zero-width characters that can cause layout issues like incorrect letter-spacing. ```jsx ``` -------------------------------- ### Enable Click-to-Edit Persistently Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use the `enableClickToEdit` prop set to `true` to persistently enable click-to-edit overlays. This makes editing overlays immediately visible. ```jsx ``` -------------------------------- ### React Router Integration Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Integrate ContentLink with React Router by providing navigation callbacks to sync the preview with the CMS. This ensures the editing experience is consistent across your application. ```jsx import { ContentLink as DatoContentLink } from 'react-datocms'; import { useNavigate, useLocation } from 'react-router-dom'; export function ContentLink() { const navigate = useNavigate(); const location = useLocation(); return ( navigate(path)} currentPath={location.pathname} /> ); } ``` -------------------------------- ### Enable Click-to-Edit via Prop Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Persistently enable the click-to-edit functionality for the ContentLink component by setting the `enabled` prop to `true`. This makes all editable content clickable. ```jsx ``` -------------------------------- ### Use useContentLink Hook Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md The `useContentLink` hook provides access to the ContentLink functionality within your components. It's useful for advanced integrations and custom UIs. ```jsx import { useContentLink } from '@datocms/react-datocms'; function MyComponent() { const { isEditingEnabled } = useContentLink(); return (
{isEditingEnabled ? 'Editing is enabled!' : 'Editing is disabled.'}
); } ``` -------------------------------- ### Reveal Stega Metadata Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Utilize the `revealStega` function to make stega-encoded metadata visible in your HTML content. This can be helpful for visual inspection during development. ```javascript import { revealStega } from '@datocms/react-datocms'; const revealedHtml = revealStega(yourHtmlContent); console.log(revealedHtml); ``` -------------------------------- ### Decode Stega Metadata Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use the `decodeStega` utility to extract stega-encoded metadata from your content. This is useful for debugging or custom integrations. ```javascript import { decodeStega } from '@datocms/react-datocms'; const metadata = decodeStega(yourHtmlContent); console.log(metadata); ``` -------------------------------- ### Next.js App Router Integration Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Integrate ContentLink with Next.js App Router by providing navigation callbacks to sync the preview with the CMS. This ensures the editing experience is consistent across your application. ```jsx 'use client'; import { ContentLink as DatoContentLink } from 'react-datocms'; import { useRouter, usePathname } from 'next/navigation'; export function ContentLink() { const router = useRouter(); const pathname = usePathname(); return ( router.push(path)} currentPath={pathname} /> ); } ``` ```jsx //app/layout.tsx import { ContentLink } from './ContentLink'; export default function RootLayout({ children }) { return ( {children} ); } ``` -------------------------------- ### Strip Stega Metadata Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Employ the `stripStega` utility to remove stega-encoded metadata from your HTML content. This is useful for cleaning up content before rendering or sending it elsewhere. ```javascript import { stripStega } from '@datocms/react-datocms'; const cleanHtml = stripStega(yourHtmlContent); console.log(cleanHtml); ``` -------------------------------- ### Expanding Clickable Area with a Parent Element Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use `data-datocms-content-link-group` to make an ancestor element the clickable target for editing, expanding the editable region beyond the immediate parent of the stega-encoded content. Ensure a group contains only one stega-encoded source to avoid collisions. ```tsx
{/* product.title contains stega encoding */}

{product.title}

${product.price}

``` -------------------------------- ### Reveal Stega Encoding with Tags Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md Use revealStega to replace stega encoding occurrences with human-readable [STEGA:/editor/...] tags. This is useful for debugging and logging. ```typescript import { revealStega } from 'react-datocms/stega'; revealStega("Hello‎world") // "Hello[STEGA:/editor/item_types/123/items/456]world" // Works on entire GraphQL responses revealStega(graphqlResponse) ``` -------------------------------- ### Creating an Independent Editable Region with Boundary Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md The `data-datocms-content-link-boundary` attribute stops upward DOM traversal for group resolution, making the element containing stega text the clickable target. This prevents merging into a parent group and creates an independent editable region. ```tsx
{/* page.title contains stega encoding → resolves to URL A */}

{page.title}

{/* page.author contains stega encoding → resolves to URL B */} {page.author}
``` -------------------------------- ### Image Component with Key for Data Updates Source: https://github.com/datocms/react-datocms/blob/master/docs/image.md When the data prop changes, the image updates like a regular img. To make the old image disappear while loading, use a key prop to force React to treat it as a new element. ```jsx ``` -------------------------------- ### Attaching Stega-Encoded Metadata to Structural Elements Source: https://github.com/datocms/react-datocms/blob/master/docs/content-link.md The `data-datocms-content-link-source` attribute attaches stega-encoded metadata to elements that cannot contain text, such as videos or iframes. The library decodes this metadata to make the element clickable for editing. ```tsx
```