prismicio / prismic-react

React components and hooks to fetch and present Prismic content
https://prismic.io/docs/technologies/homepage-reactjs
Apache License 2.0
154 stars 40 forks source link

Elegantly handle incorrect `<PrismicText>` usage with Key Text fields #149

Closed angeloashmore closed 1 year ago

angeloashmore commented 2 years ago

Is your feature request related to a problem? Please describe.

The <PrismicText> component is designed to accept and render Rich Text fields. It outputs a plain text version of its input using @prismicio/helpers's asText() helper.

A developer might reach for the <PrismicText> component for other text-related fields, such as a Key Text field. This is an invalid input, thus the component fails to handle it properly and results in an unhandled error.

Describe the solution you'd like

While <PrismicText> shouldn't be used to render plain strings (as is the case with a Key Text field), we can handle the invalid case in a more friendly way.

For example, the component could continue to throw an error when it receives an invalid input, but the message could contain an explanation of why the input is invalid and how to fix it.

The component could also pass through the input with no processing, but also print an error/warning to the console explaining that the input is unsupported.

Lastly, TypeScript users could receive an special message displayed in their code editors when passed an invalid input. This might be implemented with something like @deprecated which allows for a more friendly message than a complex TypeScript type error.

Describe alternatives you've considered

Rename <PrismicText>

The <PrismicText> component could be renamed to better reflect what it is doing. It lives within a small family of Rich Text components:

<PrismicText> could be renamed to something like <PrismicRichTextAsString>. This is verbose and ugly.

Remove <PrismicText> and move functionality into <PrismicRichText>

Alternatively, <PrismicText> could be removed if its functionality was moved into <PrismicRichText>. A prop could be added that lets a developer select between component output or string output.

<PrismicRichText field={doc.data.field} format="text" />

This is harder to parse throughout a codebase than <PrismicText> since you must read both <PrismicRichText> and format="text" to understand it is rendering a string. It also complicates the <PrismicRichText> component; it is now handling two different use cases.

Additional context

Slice Machine was providing a helpful, but incorrect, snippet for Key Text fields. It told developers to use <PrismicText> rather than using the field's value directly. While there could be a number of reasons for the error, the root problem was clear: <PrismicText>'s purpose is ambiguous.

lihbr commented 2 years ago

Awesome! I'd be for letting it fail and logging a prismic.dev message when field is of type string :)

angeloashmore commented 1 year ago

Implemented in #152.