Search code examples
node.jsreactjsreact-intl

Local Dates in Node react-intl


I am trying to set up i18n on a React App using react-intl. The app is universal rendered (so on both client and server using node). A basic example of what I have is this:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {IntlProvider, FormattedDate} from 'react-intl';

class App extends Component {
    const date = new Date();
    render() {
        return (
            <div>
                <FormattedDate value={date} />
            </div>
        );
    }
}

ReactDOM.render(
    <IntlProvider locale="en-GB">
        <App />
    </IntlProvider>,
    document.getElementById('container')
);

The server rendered formatted date is different from the client rendered date causing the react checksum to be invalid and throw the server render away. The server is sending back the en-US locale of the date and the browser is rendering the en-GB

I tried this little test in both the server and the browser:

var date = new Date();
console.log(date.toLocaleDateString('en-GB'));
console.log(date.toLocaleDateString('en-US'));

In the browser it logs:

"13/04/2016" "4/13/2016"

Which is what I'd expect but in node I get

"4/13/2016" "4/13/2016"

Which is maybe why the server rendered version of the react code is different from the browser version??

I am just guessing that this is the issue. Node is version v5.4.1


Solution

  • So in case anyone is coming up against the same issue here is what I did to solve it. Node only supports en locale by default but this is actually not the en-GB locale but rather en-US version. You can rebuild node with the icu you want - https://github.com/nodejs/node/wiki/Intl or alternativly I installed the full-icu package from npm https://www.npmjs.com/package/full-icu