1

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`),
    },
},
Cold_Class
  • 3,214
  • 4
  • 39
  • 82

1 Answers1

2

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,
    },
},
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Is there a way to provide more info on this? I tried the same exact setup as you got there, I still get the same error. I tried to pull my layout component to top level and apply it in wrapRootElement function, I got some components in my Layout component with useIntl hooks - basically if I use Layout anywhere above page level, it will throw that error. Gatsby-plugin-layout and gatsby-plugin-intl order didn't seem to make any difference as far as error –  Aug 10 '20 at 01:59
  • 1
    @NikitaTomkevich If you pull Layout over the intlProvider which you do with wrapRootElement you will get the error. If you could provide more details on your setup in a separate question that might be helpful – Shubham Khatri Aug 10 '20 at 04:35