Skip to content

Commit

Permalink
Add SSR support to i18next article (#4582)
Browse files Browse the repository at this point in the history
* Add SSR support to i18next article

* Add note

translate hoc (react-i18next) cause component not able to SSR
  • Loading branch information
joehua87 authored and KyleAMathews committed Mar 27, 2018
1 parent 05458c1 commit ed6990d
Showing 1 changed file with 49 additions and 0 deletions.
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

0 comments on commit ed6990d

Please sign in to comment.