Giter Site home page Giter Site logo

prismicio / prismic-react Goto Github PK

View Code? Open in Web Editor NEW
153.0 17.0 41.0 1.94 MB

React components and hooks to fetch and present Prismic content

Home Page: https://prismic.io/docs/technologies/homepage-reactjs

License: Apache License 2.0

JavaScript 0.76% TypeScript 99.24%
javascript typescript prismic react

prismic-react's Introduction

@prismicio/react

npm version npm downloads Github Actions CI Codecov Conventional Commits License

React components and hooks to fetch and present Prismic content.

  • 📝  Display content from Prismic like Rich Text and Link fields
  • 🍡  Render Prismic Slice Zones declaratively with React components
  • 🎣  Fetch Prismic content using React hooks

Install

npm install @prismicio/react

Documentation

To discover what's new on this package check out the changelog. For full documentation, visit the official Prismic documentation.

Contributing

Whether you're helping us fix bugs, improve the docs, or spread the word, we'd love to have you as part of the Prismic developer community!

Asking a question: Open a new topic on our community forum explaining what you want to achieve / your question. Our support team will get back to you shortly.

Reporting a bug: Open an issue explaining your application's setup and the bug you're encountering.

Suggesting an improvement: Open an issue explaining your improvement or feature so we can discuss and learn more.

Submitting code changes: For small fixes, feel free to open a pull request with a description of your changes. For large changes, please first open an issue so we can discuss if and how the changes should be implemented.

For more clarity on this project and its structure you can also check out the detailed CONTRIBUTING.md document.

License

   Copyright 2013-2022 Prismic <[email protected]> (https://prismic.io)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

prismic-react's People

Contributors

alexandrutasica avatar angeloashmore avatar arnaudlewis avatar bitmap avatar bschulz87 avatar elyobo avatar gaberogan avatar gholgot avatar hypervillain avatar levimykel avatar lihbr avatar marcmcintosh avatar mikefrancis avatar ohlr avatar petetnt avatar raph22 avatar sessa avatar srenault avatar sthobis avatar tpbowden avatar vorseek avatar xrutayisire avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prismic-react's Issues

Only standard tag element serializers supported

I tried to override elements={{[Elements.image]: CustomImage}}, but got a confusing error:

Error: img is a void element tag and must neither have children nor use dangerouslySetInnerHTML.

This is because for any custom elements, the library only provides children, which is invalid in the case of img.

Maybe in the places where createElement('...', ...) is used in richtext.js, try checking elements first?

Stop maintaining type defs

It is not best practice to maintain types if projects are not written in TypeScript:

If your types are generated by your source code, publish the types with your source code. Both TypeScript and JavaScript projects can generate types via --declaration.

Otherwise, we recommend submitting the types to DefinitelyTyped, which will publish them to the @types organization on npm.

If you move your types there, you will get tests for the types and strong support by TypeScript experts. Maintaining types with a JS project is very error prone.

Can't access property "load", window.twttr.widgets is undefined

Hey everyone,
we run into some issues with the twitter embed functionality and get error's thrown when navigating pages in our next.js app.

We use twitter analytics on our site. This means we already have window.twttr defined on all pages by default but window.twttr.widgets is not defined since this is only loaded when on a page with a twitter embed.

This is not checked correctly by the twitter embeds load check which only checks if window.twttr is present but not widgets. In some cases this causes our site to break because twttr.widgets is not loaded fast enough but the load function is still executed.

I think just adding an additional check for window.twttr.widgets in the if statement would resolve this.

export const embeds = {
  Twitter: {
    ...
    load: function() {
      if (window && window.twttr) {
        window.twttr.widgets.load();
      }
    }
  },

Serialize string (`"Hello <span>World</span>"`) to jsx

I'm defining a Custom Type with a Rich Text field,
I'm creating a Document with this Custom Type and filling the Rich Text field with Hello <span>World</span> (as a string).

When passing the data to the <RichText />, simplified like so

<RichText
  render={{
    type: ...,
    text: "Hello <span>World</span>",
    spans: ...,
  }}
/>

The output is an html element <p>Hello <span>World</span></p> where <p> is an html Element, but <span> is a string:
image

I suspect the string isn't serialized to avoid XSS attacks.

I've been trying to use htmlSerializer in combination with DOMPurify, without success.

Can this be achieved, is there an alternative?

RichText with React Native

Hi !

I have an issue when i use RichText on my React Native application.

With React Native, any text should be in a component.

Rich text return me an error if I do :
<RichText render={...} Component="Text"/>

Same things if I do :
<RichText render={...} Component={<Text />} />

Have you got an idea ?

Many thanks ;)

Error updating code to use newer render syntax, with react-dom 16.0.0

Not sure if this is an issue with prismic-reactjs + react-dom 16.0.0, or my misunderstanding the current usage-

I've inherited a react/prismic/node application that started with prismic-reactjs 0.2.0, and I have a branch where I've upgraded to prismic-reactjs 1.1.0. Because of dependencies, this has also meant updating the following other packages:
react: 15.6.1 → 16.0.0
webpack: 3.12.0 → 4.39.2
react-dom: 15.6.1 → 16.0.0
react-router-dom: 4.1.2 → 5.0.1

The original code used RichText.render like this:
{RichText.render(privacy_policy_content)}

('privacy_policy_content' is a const from this.props.data, it's an array of objects that have text inside)

With these new package versions, the render line above gives a new error (preventing the page from loading):
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. [...] Check the render method of PrivacyPolicy.

The contents of that page do still load if I use asText (but without the formatting):
{RichText.asText(privacy_policy_content)}

I see that the recommended syntax has changed for RichText.render, to this:
<RichText render={privacy_policy_content}/>

However that gives a similar error as above, just saying to check the render method of RichText (instead of PrivacyPolicy)

Debugging the error and comparing the two branches, I see that the render return method uses completely different code: in the branch with older package versions, we go to ReactCompositeComponent.js, but in this branch with newer package versions, we go to reactDom.development.js.

Has anyone reported RichText render no longer rendering arrays with react-dom 16.0.0? Have you heard of anything like this?

thanks in advance for your help!

Full code for context (though div tags aren't making it through):
`import React from 'react'
import NotFoundPage from '../Shared/NotFoundPage'
import PrismicReact from '../../../prismic-react'
import PrismicQuery from '../Utils/PrismicQuery'
import ReactGA from 'react-ga'
import {RichText} from 'prismic-reactjs'

class PrivacyPolicy extends React.Component {
constructor(props) {
super(props)
this.state = {
notFound: false,
linkResolver: null
}
}

componentDidMount() {
ReactGA.set({ page: location.pathname })
ReactGA.pageview(location.pathname)
}

render() {
if (this.props.PRISMIC_UNIVERSAL_DATA) {
const { PRISMIC_UNIVERSAL_DATA } = this.props
const { privacy_policy_content } = PRISMIC_UNIVERSAL_DATA.data
return (



{RichText.asText(privacy_policy_content)}


)
} else if (this.state.notFound) {
return
} else {
return null
}
}
}

const fetchData = PrismicQuery('privacy_policy')

export default PrismicReact.UniversalComponent({
request: (ctx, props) => fetchData(ctx, props),
component: PrivacyPolicy
})
`

Is there a way of pushing more data to the link resolver?

<RichText
  render={myDoc.data.title}
  linkResolver={linkResolver}
 />

linkResolver in this instance takes the _meta information for the inline link (uses UID as the resolver) however in my project in using a slug.

is there a way I can pass more data into the link resolver so that it uses slug to resolve?

example of graphQL:

... on PRISMIC_Page {
  _meta {
    uid
    type
    tags
    lang
  }
  slug
}

Cannot get rich Text to work

Using an example repo by Birkir

https://github.com/birkir/gatsby-source-prismic-graphql/blob/master/examples/arnaud/src/pages/index.js

Using <RichText render={data.title} linkResolver={linkResolver} />

I get

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Is there any documentation around the expected json data the component expects?

                {
                  "type": "heading1",
                  "text": "my homepage",
                  "spans": []
                }
              ]```

asText(undefined) TypeError

RichText.asText(undefined) results in the following runtime error in development mode.
On building the page it causes to fail the build.

Is this intended?

TypeError: Cannot read property 'map' of undefined
r [as asText]
node_modules/prismic-reactjs/dist/prismic-reactjs.js:871
  868 | 
  869 | var r = function (e, t) {
  870 |   var n = "string" == typeof t ? t : " ";
> 871 |   return e.map(function (e) {
  872 |     return e.text;
  873 |   }).join(n);
  874 | };

Support custom element and props in render

The .render for rich text currently forces an additional div around the rendered elements, with no ability to customise the wrapper div nor any ability to pass props to that wrapper (e.g. a className).

As of React 16, components can render fragments so for React 16 the additional wrapper is not required. If you're keeping React 15 compatibility, and want to keep the same interface for consistency, it would be useful to allow options to be passed to configure the element type to wrap with and any additional props to pass at least, e.g.

  render(richText, linkResolver, htmlSerializer, { tagName = 'div', props = {}) = {}) {
    const serializedChildren = PrismicRichText.serialize(richText, serialize.bind(null, linkResolver), htmlSerializer);
    const _props = Object.assign(propsWithUniqueKey(), props);
    return React.createElement(tagName, _props, serializedChildren);
  }

Redundant wrapping div rendered by RichText.render

The RichText.render method wraps Prismic StructuredText in a redundant div. This makes for instance using ´React.Children` helpers hard to use on rendered result.

This structured text:

[{"type":"paragraph","text":"With some text:","spans":[{"start":10,"end":19,"type":"strong"}]},{"type":"o-list-item","text":"Info 1","spans":[]},{"type":"o-list-item","text":"Info 2 and link","spans":[{"start":7,"end":15,"type":"hyperlink","data":{"link_type":"Web","url":"https://google.com"}}]},{"type":"o-list-item","text":"Info 3","spans":[]}]

Results in:

<div><p>With some <strong>rich text</strong>:</p><ol><li>Info 1</li><li>Info 2 <a href="https://sms.bromma.com/overview">and link</a></li><li>Info 3</li></ol></div>

The document says that a React fragment is used as a wrapper. Not a <div>.

Empty Paragraph throws error.

RichText parser does not like empty paragraphs

{ "type": "paragraph", "text": "", "spans": [] },

TypeError: Cannot read property 'length' of undefined

Could this be ignored rather than an error as we can't guarantee our content staff won't add empty paragraphs.

RFC: Generic React SliceZone component

RFC: Generic React SliceZone component

In this RFC, I propose a generic React SliceZone component be created and used in all React, Gatsby, and Next.js projects using Prismic Slice Zones.

<SliceZone
  slices={doc.data.body}
  components={{
    foo: FooSlice,
    bar: BarSlice,
  }}
/>

Creating a standard component leads to a consistent API design across framework integrations. It also leads to consistent and shared education efforts.

Consider the following existing implementations of Slice Zone components when reading this RFC to understand how the packages could be compared and integrated:

A general SliceZone component must have the following attributes:

  • Ability to render a list of Slices from a Prismic document.
  • A method with which users can determine which component gets rendered for a Slice.
  • Be easily customized and extended to fit a user's specific needs.
  • Follow idiomatic React practices.
  • Ability to integrate in "vanilla" React, Gatsby, and Next.js (including Slice Machine) projects.
  • Usage can be programmatically generated (think: Slice Machine or CLI integration).
  • Have deep TypeScript integration for type safety.

To achieve this, clear boundries of this component's functionality must be set.

What this component will do:

  • Accept a list of Slice objects
  • Accept a collection of React components
  • Render a React component for each Slice

What this component will not do:

  • Create network requests for Prismic content
  • Have a strict opinion on how a Slice's React component is implemented
  • Integrate deeply with a framework (framework-specific abstractions can exist within a framework-specific kit)

Example implementation

The following example implementation makes use of the new experimental @prismicio/types library. The library contains shared TypeScript types and interfaces that can be used across TypeScript projects. In this example, we're using it for its generic Slice type.

import * as React from 'react'
import * as prismicT from '@prismicio/types'

type IterableElement<TargetIterable> = TargetIterable extends Iterable<
  infer ElementType
>
  ? ElementType
  : never

export interface SliceComponentProps<
  Slice extends prismicT.Slice = prismicT.Slice,
  TContext = unknown
> {
  slice: Slice
  context?: TContext
}

export type SliceZoneProps<TSlices extends prismicT.SliceZone, TContext> = {
  slices: TSlices
  components: Partial<
    Record<
      IterableElement<TSlices>['slice_type'],
      React.ComponentType<SliceComponentProps>
    >
  >
  defaultComponent?: React.ComponentType<SliceComponentProps>
  context?: TContext
}

const MissingSlice = ({ slice }: SliceComponentProps) => (
  <span>Could not find a component for Slice type {slice.slice_type}</span>
)

export const SliceZone = <TSlices extends prismicT.SliceZone, TContext>({
  slices,
  components,
  defaultComponent = MissingSlice,
  context,
}: SliceZoneProps<TSlices, TContext>) => {
  return (
    <>
      {slices.map((slice) => {
        const Comp = components[slice.slice_type] || defaultComponent

        return <Comp slice={slice} context={context} />
      })}
    </>
  )
}

Items of note:

  • SliceComponentProps is the normalized React props interface for all Slice React components. It contains the full Slice data object and an optional user-defined context value. The context value can contain anything a user needs to send down to a Slice's component.

  • SliceZoneProps is properly typed, but not too strictly. It accepts a list of Slice objects, a record of Slice types mapped to React components, a default component if the map does not contain a component for a Slice, and an optional user-provided context value.

  • MissingSlice provides helpful information during development and is used as the default Slice component.

  • SliceZone is overwhelmingly simple. Its flexibility comes in the way of using JavaScript's language features.

Example Slice component

Like above, we are using @prismicio/types for its generic Slice type and collection of Prismic field types.

It references the SliceComponentProps interface defined in the above example.

import * as React from 'react'
import * as prismicT from '@prismicio/types'
import { RichText } from 'prismic-reactjs'

type FooSliceProps = SliceComponentProps<
  prismicT.Slice<
    'foo',
    {
      title: prismicT.TitleField
      number: prismicT.NumberField
    }
  >
>

export const FooSlice = ({ slice }: FooSliceProps) => (
  <RichText render={slice.primary.title} />
)

type BarSliceProps = SliceComponentProps<
  prismicT.Slice<
    'bar',
    {
      geopoint: prismicT.GeoPointField
      embed: prismicT.EmbedField
    }
  >
>

export const BarSlice = ({ slice }: BarSliceProps) => (
  <span>{slice.primary.geopoint.latitude}</span>
)

Component flexibility

In the previous example, SliceComponentProps is used to type the components. Slice component do not need to adhere to this interface. It is, however, what will be passed to the provided component as part of SliceZone's rendering process.

To use a different prop interface for the Slice component, one can adjust the component map provided to SliceZone.

<SliceZone
  slices={doc.data.body}
  components={{
    foo: ({ slice, context }) => (
      <FooSlice foo={RichText.asText(slice.primary.title)} bar={context.baz} />
    ),
    bar: BarSlice,
  }}
/>

If such a behavior becomes common within an application, an abstraction can be created. Ideally this abstraction is created by a user, not provided by the library.

// src/slices/Foo.tsx

import * as React from 'react'
import * as prismicT from '@prismicio/types'
import { RichText } from 'prismic-reactjs'

import { Context } from '../types'

type FooSliceProps = {
  foo: string
  bar: number
}

const FooSlice = ({ foo, bar }: FooSliceProps) => (
  <h1>{bar === 10 ? foo : 'not 10'}</h1>
)

export default FooSlice

type FooSliceData = prismicT.Slice<
  'foo',
  {
    title: prismicT.TitleField
    number: prismicT.NumberField
  }
>

export const mapSliceToProps = ({
  slice,
  context,
}: SliceComponentProps<FooSliceData, Context>) => ({
  foo: RichText.asText(slice.primary.title),
  bar: context.baz,
})
// src/App.tsx

import * as React from 'react'

import * as FooSlice from './slices/Foo'
import * as BarSlice from './slices/Bar'

type WithSliceZoneMapperModule = {
  default: React.ComponentType
  mapSliceToProps?: (SliceComponentProps) => Record<string, unknown>
}

const withSliceZoneMapper = ({
  default: Comp,
  mapSliceToProps,
}: WithSliceZoneMapperModule) => (sliceComponentProps: SliceComponentProps) => {
  if (mapSliceToProps) {
    return <Comp {...mapSliceToProps(sliceComponentProps)} />
  }

  return <Comp {...sliceComponentProps} />
}

export const App = () => (
  <SliceZone
    slices={doc.data.body}
    components={{
      foo: withSliceZoneMapper(FooSlice),
      bar: BarSlice,
    }}
    context={{ baz: 10 }}
  />
)

Generatable

To be viable, this component must work with generated code. Inversely, the code required by the component must be easy to generate. These requirements come from the need to integrate this component with Slice Machine.

  1. Use higher-level types from @prismicio/types to simplify generated types.
  2. Organize component exports systematically (for example, all Slices could be imported and exported through one file).
  3. Include as little code as possible in generated code.
  4. Perform as little magic as possible in generated code.
  5. Don't make a black box. Simplify instead.

Final comments

This general component is low-level enough to be used in any React project using Prismic. It does not require TypeScript usage, but users will benefit greatly through its use.

Topics like default props (linked issue is about Vue.js but applies here as well) become something that can be handled via React, not the Slice Zone component.

None of the code presented here has been tested or run. Please don't paste this into a file and wonder why it doesn't work. 😅 This is all open for discussion!

RichText Component does not work with gatsby build if render object contains embed

when trying to build a gatsby site with posts having embeds (except youtube) in doc.node.content which return <RichText render={doc.node.content} /> the process throws

ERROR #95312 

"window" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html


  12 | 
  13 |     return target;
> 14 |   };
     | ^
  15 | 
  16 |   return _extends.apply(this, arguments);
  17 | }


  WebpackError: ReferenceError: window is not defined
  
  - extends.js:14 e
    node_modules/@babel/runtime/helpers/extends.js:14:1
  
  - extends.js:16 eval
    node_modules/@babel/runtime/helpers/extends.js:16:1
  
  - extends.js:6 Object.u [as serialize]
    node_modules/@babel/runtime/helpers/extends.js:6:1

{RichText.asText(doc.node.content)} works just fine, though.

package.json:

{
  "name": "gatsby-starter-default",
  "private": true,
  "description": "A simple starter to get up and developing quickly with Gatsby",
  "version": "0.1.0",
  "author": "Kyle Mathews <[email protected]>",
  "dependencies": {
    "@emotion/core": "^10.0.17",
    "@emotion/styled": "^10.0.17",
    "dayjs": "^1.8.16",
    "gatsby": "^2.13.73",
    "gatsby-image": "^2.2.10",
    "gatsby-plugin-emotion": "^4.1.5",
    "gatsby-plugin-manifest": "^2.2.6",
    "gatsby-plugin-offline": "^2.2.7",
    "gatsby-plugin-postcss": "^2.1.6",
    "gatsby-plugin-react-helmet": "^3.1.4",
    "gatsby-plugin-sharp": "^2.2.13",
    "gatsby-source-filesystem": "^2.1.11",
    "gatsby-source-prismic": "^2.3.0-alpha.3",
    "gatsby-source-prismic-graphql": "^3.4.0-beta.1",
    "gatsby-transformer-sharp": "^2.2.7",
    "lost": "^8.3.1",
    "minireset.css": "0.0.5",
    "prismic-javascript": "^2.1.1",
    "prismic-reactjs": "^1.1.0",
    "prop-types": "^15.7.2",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-helmet": "^5.2.1",
    "react-responsive": "^8.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.5.5",
    "@storybook/addon-actions": "^5.1.11",
    "@storybook/addon-links": "^5.1.11",
    "@storybook/addons": "^5.1.11",
    "@storybook/react": "^5.1.11",
    "babel-loader": "^8.0.6",
    "prettier": "^1.18.2"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve -H 0.0.0.0",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing \"",
    "storybook": "start-storybook -h 0.0.0.0 -p 6006",
    "build-storybook": "build-storybook"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-default"
  },
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby/issues"
  }
}

Cannot read property 'map' of undefined

I'm sourcing prismic via gatsby-source-prismic

I'mm trying to render like this:
{items.map((item, index) => (

  <RichText render={item.content} />

))}

Seems to be from line 588 from prismic-reactjs.js
"var t = e.spans.map(function (t) {"

I have rich text in a repeatable slice.

Any thoughts would be much appreciated.

RichText.asText() should not throw error if no content is passed

If a field is left blank in Prismic and that field is rendered using RichText.asText() and error is thrown

TypeError: Cannot read property 'map' of undefined…

This requires that every field needs to be checked before being rendered which makes for clumsy code.

If would be great if asText returned and empty string instead.

Unable to handle multiple stylings

The kit currently is unable to handle multiple stylings of the same text in a Rich Text field.

For example, if you put everything in bold, and one part of the text in italic on top of the already bold, it renders only the strong tag, the em tag is missing.

Along with this if you put text in bold, and I set a link on 2 different words on top of the bold, only the last link will be rendered to an anchor tag.

unsafe eval

similar to react-javascript it seems this bundle isn't csp friendly due to unsafe - eval,

a pr is up for react-javascript to fix it, can a similar thing be done here?

prismicio/prismic-client#97

Thanks!

Expose serialisation functions

If I'm supposed to be able to override singular element type serialisation functions, it would be great to be able to delegate all other types of elements into this code-base. Hence; if you could expose your serialisers, it would be appreciated.

Including polyfills increases bundle size

Not an issue but a suggestion for improvement:

Based on bundlephobia.com, bundle size has recently increased from 71KB minified (1.0.0) to 217KB minified (1.0.1), which is a twofold increase. I guess it has mainly to do with the now bundled polyfills.

It seems to be best practice now to indicate in the README when polyfills are required but let the user decide how to implement them (if at all) - rather then bundling them directly. Otherwise the client bundle gets bloated by various polyfills.

fetchLinks Unexpected behaviour JS API

Unexpected behaviour for the option "fetchLinks".

From the docs I expected that the option is available for all endpoints.

This does not work:

    const response = await API.query(
      Prismic.Predicates.at('my.blog_post.uid', slug, {
        fetchLinks: [
          'author.picture',
          'author.test',
          'author.firstname',
          'author.surname',
          'author.short_description'
        ]
      })
    );

This does work:

    const response = await API.getByUID('blog_post', slug, {
      fetchLinks: [
        'author.picture',
        'author.test',
        'author.firstname',
        'author.surname',
        'author.short_description'
      ]
    });

Please add a more explicit definition to the docs of available options for each endpoint.

Date utility overrides global Date constructor

When importing the Date utility, the global js Date constructor is overwritten. The utility can be renamed on import, but this seems like dangerous practice. Consider renaming to ParseDate or ConvertDate or something else that better indicates the function.

Breaks with CSP

This might not be your fault but when I'm using Gatsby with your library my CSP complains that it needs unsafe-eval:

Uncaught (in promise) EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'sha256-6vNRX+9q2xXLVUZlB38JyTMj0RbBVK9hF78wr2cG+qU=' 'sha256-5TUZ2Dus6dN9Z5l9lYGlzJQuP+TNDL7/J7wYBS0C6/A='".

    at Object._ (prismic-reactjs.js:473)
    at t (prismic-reactjs.js:62)
    at ./node_modules/object-assign/index.js (prismic-reactjs.js:256)
    at factory (prismic-reactjs.js:8)
    at Object.237 (prismic-reactjs.js:6)
    at s (bootstrap:89)
    at Module.225 (component---src-components-post-page-index-js-369e6c4c360a51cbbf29.js:1)
    at s (bootstrap:89)

Wonder if there is a way round this?

Customize RichText.render output without re-implementing an HTML serializer

Hi Prismic team, and thanks for the SDK 🙂

This is not a bug report, more of a feature request.

I'm using RichText.render to render rich text content from Prismic as HTML, and I need to access my paragraphs (<p> tags) so that I can add class names to them. From what I've understood of the documentation, the way to do so is to implement an HTML serializer myself and pass it to RichText (used as a React component).

The issue is that to change the output of a single element, I need to re-implement an entire serializer. Sure I could copy the code from the Prismic sources (or the example from the docs), but if I do, I won't benefit from bug fixes or improvements of the default HTML serializer from this SDK.

Could we imagine a callback as a second parameter of RichText.render (à la serializeHyperlink) to run user code in the serializer? Something like:

RichText.render(html, (type, element, content, children, index) => {
  if (type === Elements.paragraph) {
    return React.createElement('p', { className: 'paragraph-class' }, children);
  }
});

The callback would run in the serialize function, allowing users to hook into it.

Another approach, to avoid growing the surface API, could be to expose the default HTML serializer (it's currently private). This way, users can implement their own serializer by wrapping Prismic one, so all they have to do is add their custom code. For example:

// other imports
import { htmlSerializer } from 'prismic-reactjs';

function customHtmlSerializer(type, element, content, children, key) {
  if (type === Elements.paragraph) {
    return React.createElement('p', { className: 'paragraph-class' }, children);
  }

  htmlSerializer(type, element, content, children, key);
}

<RichText render={html} htmlSerializer={customHtmlSerializer} />;

Does it make sense?

I'd be happy to PR if any of these options sound interesting to you.

Link. url do not support graphql field return

the prismic gql return object as following {"_linkType":"Link.web","__typename":"_ExternalLink"}
then when you try to use link to render the url it throw

TypeError: Cannot read property 'link_type' of null
    at Object.url (webpack://PrismicReactjs/./node_modules/prismic-helpers/dist/prismic-helpers.min.js?:68:33)

RichText.asText prepends newline char to string

This is the object that is returned from Prismic:

[{"type":"heading1","text":"Velkomin","spans":[]}]

This is what RichText.asText() outputs:

"\n Velkomin"

Is this a bug or expected behaviour? I would expect the output to be "Velkomin".

Custom props on the final component

Hi there,
Maybe I didn't saw the option to give props (like className) to the the final component. My use case is styling components with styled-jsx, I need to set the className prop on the final component that will be styled.
Have a nice day.

Firefox and Chrome don't have same nesting order for links with labels.

Hi,
I noticed a problem where RichText is rendering components differently for Firebox vs Chrome. Already noticed this on 2 clients' websites. Basically if you add a label to the link in Rich Text it will nest them differently depending on the browser.

From Firefox:
image
From Chrome:
image

Currently resolving it by adding click event handlers to buttons that have links inside.

Please push the tags

Tag 1.3.1 and 1.3.2 are missing. I guess you have tagged the code before release but forgot to push the tags to github. Please do so, I need to compare the versions.

Typescript types...?

Hi guys, I notice that prismic-javascript has typings available. Any plans to release typings for this?

Prop type validation is wrong for RichText Component prop

Currently the prop type of the Component prop of the RichText component is node which is wrong and trigger a warning when choosing a valid React component. The code works, just the validation is wrong. The right prop type should be elementType instead.

A PR is ready if someone could grant me access.

Gatsby `e.spans is undefined`

Hey!

I am in the process of migrating from gatsby-source-prismic-graphql to gatsby-source-prismic

"gatsby-source-prismic": "^3.3.6",
"prismic-reactjs": "^1.3.3",

I am almost done but I have a weird issue with RichText render={content}

I got this data from the GraphQL query

[
  {
    "type": "paragraph",
    "text": "Agnès VARDA est donc née en Belgique en 1928. Après avoir rejoint la ville de Sète avec ses parents en 1940, elle se rend sur Paris pour y passer son baccalauréat et, par la suite, pour étudier la photographie à l’école des beaux-arts du Louvres. Son talent est très rapidement repéré par les Galeries LAFAYETTE et la SNCF qui l'engagent comme photographe pour leur société au début des années 1950.",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "heading2",
    "text": "Membre de “La nouvelle Vague” ",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "C’est en 1954 qu’elle commence une carrière de cinéaste avec son film La Pointe Courte, nom éponyme d’un quartier de Sète, avec Silvia MONFORT et Philippe NOIRET jouant les rôles principaux. Ce premier long métrage met en avant le beau quartier sétois à travers plusieurs plans magnifiquement bien cadrés.",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "Ce film permet à Agnès d’être reconnue à part entière comme une membre fondatrice de “la Nouvelle Vague”. Cette expression est née dans la presse française à la toute fin des années 1950. Elle désigne en tout et pour tout les films présentés au festival de Cannes de 1959. En effet, c’est à cette époque que plusieurs techniques cinématographiques sont redécouvertes ou revisitées. Les plans sont plus mobiles, la couleur remplace lentement et progressivement le noir et blanc (les premières pellicules de couleurs sont crées en 1928 par l’entreprise américaine Technicolor) et l’apparition des “Films-documentaires” plait à un large public.",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "Le talent de Agnès est si fabuleux, qu’elle a reçu ces derniers prix alors que sa carrière n’était pas terminée ! Seule la nature a eu raison de notre artiste nationale si puissante, le 29 mars 2019, il y a tout juste 2 ans ... Reposez en paix (coeur). ",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "Son film autobiographique Varda par Agnès retrace toute l’histoire d’Agnès, par Agnès. ",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "À vous, pionnière du mouvement de “la Nouvelle Vague”, à vous qui avez été une idole pour tant de personnes, des artistes, des cinéastes, des militant.e.s féministes !",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "Un grand merci !",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "Par CAUJOLLE Jordan",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "",
    "url": null,
    "alt": null,
    "copyright": null
  },
  {
    "type": "paragraph",
    "text": "",
    "url": null,
    "alt": null,
    "copyright": null
  }
]

And the error is this one

image

Do you have an idea on how to fix the problem?

RichText component seems to not format text properly

Hello there,

first of, great job on Prismic 👍

I have a weird layout error, please check out this this video

Until the 20 sec mark, the content is rendered by the RichText component, and you can see the layout is kind of broken.

And you have a look at the devtools, you can see that when I resize the panel, the text does not wrap, I have to scroll to read it.

After the 20sec mark, it is the same website, except the data was hardcoded, rather than fetched from the Priscmic API, you can see that the text is wrapped properly, and thus the layout is not broken.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.