injectIntl causing error after adding gatsby-plugin-layout

708 Views Asked by At

In order to translate my site I'm injecting intl like this in my layout.js file:

import React from "react";
import { injectIntl } from "gatsby-plugin-intl";

const Layout = ({intl}) => (
    {intl.formatMessage({id: "history_text"})}
);

export default injectIntl(Layout)

But after I added gatsby-plugin-layout to my project (based on this example) I get this error:
Error: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

How can I get rid of this error while keeping my translations?

This is the relevant gatsby config part:

{
    resolve: `gatsby-plugin-intl`,
    options: {
        path: `${__dirname}/src/locale`,
        languages: [`en`, `de`],
        defaultLanguage: `de`,
        redirect: false,
    },
},
{
    resolve: `gatsby-plugin-layout`,
    options: {
        component: require.resolve(`./src/components/layout.js`),
    },
},
1

There are 1 best solutions below

2
On BEST ANSWER

gatsby-plugin-layout and gatsby-plugin-intl both make use of wrapPageElement API to create a wrapper.

Now the plugins in gatsby are executed from top down and hence you need to define gatsby-plugin-layout before gatsby-plugin-intl so that the IntlProvider provider used by gatsby-plugin-intl wraps the Layout component and it is being able to use the injectIntl HOC

{
    resolve: `gatsby-plugin-layout`,
    options: {
        component: require.resolve(`./src/components/layout.js`),
    },
},
{
    resolve: `gatsby-plugin-intl`,
    options: {
        path: `${__dirname}/src/locale`,
        languages: [`en`, `de`],
        defaultLanguage: `de`,
        redirect: false,
    },
},