# React components

Render Mojimoto rich text, images, links and page sections in React with the components and hooks in @mojimoto/react.

`@mojimoto/react` turns the JSON from the [Delivery API](/docs/api/delivery) into React elements. It has components for rich text, images, links and page sections, and hooks for fetching in the browser. It works with React 18 and 19, in Server and Client Components. In Next.js, add [@mojimoto/next](/docs/frameworks/nextjs) for fetching and preview.

This page describes version 0.3.0.

## Install

```bash
npm i @mojimoto/react @mojimoto/client
```

## A first example

```tsx components/Article.tsx
import { MojiImage, MojiRichText, type MojimotoDocument, type MojiRichTextValue } from '@mojimoto/react'

type Media = { url: string; alt: string | null; width: number | null; height: number | null }

type Post = MojimotoDocument<'post', { title: string; cover: Media | null; body: MojiRichTextValue }>

export function Article({ post }: { post: Post }) {
  return (
    <article>
      <h1>{post.data.title}</h1>
      <MojiImage field={post.data.cover?.url} alt={post.data.cover?.alt ?? ''} />
      <MojiRichText field={post.data.body} />
    </article>
  )
}
```

The types here are written by hand. [Generated types](/docs/tools/generated-types) give you the same for your whole model.

## Render rich text

`MojiRichText` renders a `rich_text` field as plain HTML elements: `p`, `h1` to `h6`, `ul`, `ol`, `pre`, `table`, `img`, `strong`, `em` and `a`.

| Prop | Type | Description |
| --- | --- | --- |
| `field` | `MojiRichTextValue` or `null` | The field value. |
| `components` | `MojiRichTextComponents<ReactNode>` | Your own element for any block or span. |
| `linkResolver` | `(link) => string` | Turns a link to another entry into an `href`. |
| `fallback` | `ReactNode` | Rendered when the field is empty. Nothing by default. |

Override only the nodes you want to change. You do not need to set `key`.

```tsx
<MojiRichText
  field={post.data.body}
  components={{
    heading2: ({ children }) => <h2 className="section-title">{children}</h2>,
    image: ({ node }) => <img src={node.url} alt={node.alt ?? ''} loading="lazy" />,
  }}
  linkResolver={(link) => `/${link.uid}`}
  fallback={<p>Nothing here yet.</p>}
/>
```

The entries and what each receives are listed under [Change the HTML for one node](/docs/frameworks/rich-text#change-the-html-for-one-node). Here they return elements, not strings.

Two things to know:

- A soft line break is a `\n` in the text. It only shows if the element has `white-space: pre-line` in your CSS.
- An `embed` block is rendered with `dangerouslySetInnerHTML`, using the HTML stored in the field. Override `embed` if that HTML can come from somewhere you do not trust.

## Render plain text

`MojiText` renders a rich text field with the formatting removed, for a heading or a summary.

```tsx
<MojiText field={post.data.summary} as="p" />
```

| Prop | Type | Description |
| --- | --- | --- |
| `field` | `MojiRichTextValue` or `null` | The field value. |
| `as` | element or component | What to wrap the text in. Without it the text is rendered bare. |
| `separator` | `string` | Placed between blocks. A space by default. |
| `fallback` | `string` | Used when the field is empty. |

## Render an image

`MojiImage` renders an `img`. Its `field` is a URL string, or an image block from a rich text field. A `media` field is delivered as an object, so pass its `url`:

```tsx
<MojiImage field={post.data.cover?.url} alt={post.data.cover?.alt ?? ''} className="cover" loading="lazy" />
```

| Prop | Type | Description |
| --- | --- | --- |
| `field` | `string`, an image block or `null` | What to show. Nothing is rendered when it is empty. |
| `alt` | `string` | The alt text. For an image block it falls back to the block's own `alt`, then to an empty string. |

Any other `img` attribute is passed on, except `src`, `width` and `height`.

> **Note:** `MojiImage` does not take `width` and `height`. To stop the page moving as images load, render the `img` yourself with the numbers the API gives you.

```tsx
const cover = post.data.cover

return cover ? (
  <img src={cover.url} alt={cover.alt ?? ''} width={cover.width ?? undefined} height={cover.height ?? undefined} />
) : null
```

## Render a link

`MojiLink` renders a link value as an `a`. `MojiRichText` uses it for every link in the text. There is no link field type, so use it directly only when you hold a link value yourself, such as a span's `data`.

| Prop | Type | Description |
| --- | --- | --- |
| `field` | `MojiLinkValue` or `null` | The link, such as `{ link_type: 'Web', url: 'https://example.com' }`. |
| `linkResolver` | `(link) => string` | Turns a link to another entry into an `href`. |
| `as` | component | Render through this in place of `a`. It receives `href`. |

Other anchor attributes and `children` are passed on. A link with `target="_blank"` gets `rel="noopener noreferrer"`.

To send the links in rich text through Next's `Link`:

```tsx
import Link from 'next/link'
import { MojiLink, MojiRichText, type MojiLinkValue } from '@mojimoto/react'

<MojiRichText
  field={post.data.body}
  components={{
    hyperlink: ({ node, children }) => (
      <MojiLink field={node.data as MojiLinkValue} as={Link}>
        {children}
      </MojiLink>
    ),
  }}
/>
```

A component that takes `to`, like React Router's `Link`, needs a small wrapper that maps `href` to `to`. `resolveHref(link, linkResolver)` is exported if you only want the URL.

## Render blocks and sections

`SliceZone` renders a list of sections by matching each one's `type` to a component. It takes the blocks of a `blocks` field, or the entries of a `references` field.

```tsx
import { SliceZone, type BlockComponents } from '@mojimoto/react'

const components: BlockComponents = {
  hero: ({ slice }) => <h1>{slice.data.heading as string}</h1>,
  quote: ({ slice }) => <blockquote>{slice.data.text as string}</blockquote>,
}

export function Sections({ page }: { page: Page }) {
  return <SliceZone slices={page.data.sections} components={components} />
}
```

| Prop | Type | Description |
| --- | --- | --- |
| `slices` | array or `null` | The blocks or entries, in order. |
| `components` | `BlockComponents` or `SliceComponents` | A component for each `type`. |
| `context` | anything | Passed to every component as `context`. |
| `fallback` | component | Used for a `type` with no component. |

Each component receives `slice` (the block or entry), `index`, `slices` and `context`. Type the map as `BlockComponents` for a `blocks` field and `SliceComponents` for a `references` field.

A linked entry beyond the request's `depth` has no `data` and is skipped, so ask for enough [depth](/docs/concepts/links). A `type` with no component and no `fallback` renders nothing, with a console warning in development.

## Share settings with a provider

`MojimotoProvider` sets defaults for everything below it: a `linkResolver`, `richTextComponents` for every `MojiRichText`, and the `client` the hooks use.

```tsx app/providers.tsx
'use client'

import type { ReactNode } from 'react'
import { createClient } from '@mojimoto/client'
import { MojimotoProvider } from '@mojimoto/react'

const cms = createClient({
  endpoint: 'https://mojimoto.com/api/v1',
  project: 'acme',
  token: 'mjmt_your_read_token',
})

export function Providers({ children }: { children: ReactNode }) {
  return (
    <MojimotoProvider client={cms} linkResolver={(link) => `/${link.uid}`}>
      {children}
    </MojimotoProvider>
  )
}
```

A component's own props win over the provider, and the provider wins over the built-in output.

> **Warning:** This client runs in the browser, so its token is public. Give it a token with only the `read` ability.

## Fetch in the browser

The hooks fetch from a Client Component, using the provider's client. They cancel the request on unmount and fetch again when their arguments change.

```tsx components/LatestPosts.tsx
'use client'

import { useMojiQuery } from '@mojimoto/react'

export function LatestPosts() {
  const { data, error, loading } = useMojiQuery({ type: 'post', sort: '-updated_at', perPage: 5 })

  if (loading) return <p>Loading</p>
  if (error) return <p>{error.message}</p>

  return (
    <ul>
      {data?.map((post) => (
        <li key={post.id}>{String(post.data.title)}</li>
      ))}
    </ul>
  )
}
```

| Hook | Returns |
| --- | --- |
| `useMojiQuery(options)` | `{ data, error, loading }`. `data` is the array of entries. The options are those of the client's [query](/docs/frameworks/javascript#list-entries). |
| `useMojiDocument(type, uid, options)` | `{ data, error, loading }`. `data` is the entry, or `null` when there is none. The options are `lang` and `preview`. |
| `useMojimotoClient()` | The provider's client. Throws if there is none. |
| `useMojimotoContext()` | Everything the provider was given. |

## Server Components

- `MojiRichText`, `MojiText`, `MojiImage`, `MojiLink` and `SliceZone` render in Server Components.
- `MojimotoProvider` and the hooks need a Client Component. The provider throws an error that says so if a Server Component renders it.
- A component rendered on the server cannot see the provider. Pass `linkResolver` and `components` as props there.

## Other exports

`asText` and `asHTML` are re-exported from [@mojimoto/richtext](/docs/frameworks/rich-text). The types are `MojiRichTextValue`, `MojiLinkValue`, `MojiLinkResolver`, `MojiRichTextComponents`, `MojimotoDocument`, `MojimotoBlock`, `MojimotoSlice` and `MojimotoClient`, the props of each component (`MojiRichTextProps`, `MojiTextProps`, `MojiImageProps`, `MojiLinkProps`, `SliceZoneProps`, `MojimotoProviderProps`), `SliceComponent`, `SliceComponentProps`, `MojimotoContextValue` and `AsyncState`.
