Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SSR support to i18next article #4582

Merged
merged 2 commits into from
Mar 27, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions docs/blog/2017-10-17-building-i18n-with-gatsby/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,55 @@ The `handleLanguageChange` function just wraps the `react-i18n` function passed
in as a prop through `translate`. Pretty much everything is handled for us.
Hooray! 🎉

## SSR

To let it render the content into html, you need to load i18n namespaces (using `i18n.loadNamespaces`) before render

### With redux

```js
// gatsby-ssr.js

import React from 'react'
import { Provider } from 'react-redux'
import { renderToString } from 'react-dom/server'
import i18n from './src/i18n'

import createStore from './src/state/createStore'

exports.replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
i18n.loadNamespaces(['common'], () => {
const store = createStore()
const ConnectedBody = () => (
<Provider store={store}>{bodyComponent}</Provider>
)
replaceBodyHTMLString(renderToString(<ConnectedBody />))
})
}
```

### Without redux

> Not yet tested

```js
// gatsby-ssr.js

import React from 'react'
import { renderToString } from 'react-dom/server'
import i18n from './src/i18n'

import createStore from './src/state/createStore'

exports.replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
i18n.loadNamespaces(['common'], () => {
replaceBodyHTMLString(bodyComponent)
})
}
```

> `translate` hoc from react-i18next cause page / component not able to SSR. I make it works by import i18n & use i18n.t

## Finishing up

As you can see, i18n in Gatsby is actually pretty simple when you know how! We
Expand Down