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

Custom `<PrismicRichText>` components do not automatically apply the `key` prop #114

Closed angeloashmore closed 2 years ago

angeloashmore commented 2 years ago

Versions

Reproduction

The following component will print a "React key missing" warning to the console. Note that the <h1> component does not have a key prop.

const Page = () => {
    return (
        <PrismicRichText
            field={[
                {
                    type: "heading1",
                    text: "My heading",
                    spans: [],
                },
            ]}
            components={{
                heading1: ({ children }) => <h1 className="heading">{children}</h1>,
            }}
        />
    );
};

The following component, which now passes the key prop provided as an argument, does not print the key warning.

const Page = () => {
    return (
        <PrismicRichText
            field={[
                {
                    type: "heading1",
                    text: "My heading",
                    spans: [],
                },
            ]}
            components={{
                heading1: ({ children, key }) => (
                    <h1 className="heading" key={key}>
                        {children}
                    </h1>
                ),
            }}
        />
    );
};

Steps to reproduce

Add the above code to a React project and check the console.

What is expected?

When using custom components, passing a key prop explicitly should not be required. It should be applied implicitly (but allow overriding explicitly).

This could be achieved by using a higher order function on the serializer built using the components prop value.

What is actually happening?

React warns the developer that a key prop is missing. The key is not applied automatically by <PrismicRichText>

(cc @asyarb)

angeloashmore commented 2 years ago

Fixed in #118. The fix will be published in the next release.

angeloashmore commented 2 years ago

This has been published in v2.0.4 🎉