Giter Site home page Giter Site logo

react-intl-redux's Introduction

React Intl Redux

Redux binding for React Intl.

Building idiomatic React Redux Application by having translations in store and dispatching action to update it.

Installation

npm install react-intl-redux react react-intl react-redux redux --save

Usage

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { FormattedNumber } from 'react-intl'
import { Provider, intlReducer } from 'react-intl-redux'
import reducers from '<project-path>/reducers'

const reducer = combineReducers({
  ...reducers,
  intl: intlReducer,
})

const store = createStore(reducer)

const App = () => (
  <Provider store={store}>
    <FormattedNumber value={1000} />
  </Provider>
)

ReactDOM.render(<App />, document.getElementById('container'))

Provide locale and messages on load

You should provide a different locale and messages if your user is not using en locale.

const initialState = {
  intl: {
    locale: 'it',
    messages: {
      'app.greeting': 'Ciao!',
    },
  },
  // ...other initialState
}
const store = createStore(reducer, initialState)

Refer to the initial-locale example for more details.

Switch locale and messages on request

You could also switch locale on user's request by dispatching updateIntl action.

import { updateIntl } from 'react-intl-redux'

store.dispatch(updateIntl({
  locale,
  messages,
}))

React Intl in browsers only contain locale data for basic English by default, see Loading Locale Data for loading locale data in browsers.

Provider vs IntlProvider

In most cases, react-intl-redux will be wrapped immediately after Provider from react-redux. For convenient, react-intl-redux provides Provider to do that for you.

However, if you don't want it, you could do it manually via IntlProvider. For example,

import React from 'react'
import { IntlProvider } from 'react-intl-redux'
import { Provider } from 'react-redux'

const App = () => (
  <Provider store={store}>
    <IntlProvider>
      <App />
    </IntlProvider>
  </Provider>
)

Formatting Data

react-intl provides two ways to format data, see the official docs.

To change formats through React components,

import { updateIntl } from 'react-intl-redux'

store.dispatch(updateIntl({
  locale,
  formats,
  messages,
}))

Use with redux-immutable

See the usage in test.

Examples

There are some examples under the examples folder for reference.

Troubleshooting

  1. Why my connected component does not update after locale change?

By default, locale is used as key for IntlProvider, which will trigger re-render when locale changes, things should just work.

If it doesn't, here are few solutions could be tried,

  • Do a forceUpdate after changing locale.
  • Mark the connecting compoent {pure: false}.
  • Pass locale in props.
  • Set key when dispatching updateIntl.
  • Provide custom intlSelector for IntlProvider.
  1. How to use intl in asynchronous action?

A simple solution would be retrive intl object using injectIntl and pass it in the action payload.

react-intl-redux's People

Contributors

bensampaio avatar filipediasf avatar geovie avatar jessnah avatar macca16 avatar mewdriller avatar nate-summercook avatar ovr avatar ratson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-intl-redux's Issues

Conflicting types due to usage of @types/react-intl

The react-intl package now provides its own types, rendering the @types/react-intl outdated. This package's usage of @types/react-intl results in the IntlProvider using the old outdated types, resulting in the wrong set of prop types.

Please remove @types/react-intl and upgrade the version of react-intl being used to allow the correct types to flow through.

formats prop for IntlProvider

Hello! Thanks for great and simple to use module.

There is a feature in react-intl (not enough documented as far as I know): formats prop for <IntlProvider>. It adds ability to add custom formatting for currencies in <FormattedNumber />: formatjs/formatjs#539 (comment)

It would be great if we could add this feature to this module as well. Is there a need for it?

How to load multiple languages at once?

Hi,

thanks for this package. It works great. Just one caveat that I'd like to address.

How could I load all my languages at once (init), save them in redux, and then when changing locale using updateIntl having the proper messages being used.
In redux intl.messages could be an object looking like so:

{
    en: [...en],
    fr: [...fr],
    de: [...de]
}

Also I'd like to understand the use of defaultLocale during initialization if you can't load multiple languages at once? If I init like this:

const messages = {
  fr: frenchMessages,
  en: englishMessages,
  de: deutschMessages,
};

const initialState = {
  intl: {
    defaultLocale: 'en',
    locale: localStorage.locale,
    messages: messages[localStorage.locale],
  },
};

Then defaultLocale is useless as I can't load the proper messages for that default locale.

I hope I'm clear

Thanks for any help

reference messages via props

I've built an app using React-Intl and now I'm trying to use your redux variant. When I referenced messages not inside DOM elements but simply as JS injections I would write a line of code similar to this:

this.props.intl.formatMessage({ id: 'greeting', defaultMessage: "not translated" })

This came in handle for this such as the placeholder of an input textfield.

However, I am unable to do the same in this case because I do not have intl on the this.props.

Can you suggest how I may do something similar in this case?

Warning: Failed Context Types error

Hi

Im integrating your module and everything works as expected except I get the following warning in the console:

Warning: Failed Context Types: Required context intl.now was not specified in FormattedMessage.

The formattedMessage component is using the same version of 'react-intl' that you are using as part of the module and the provider component is wrapped around around React-router component. Not sure if that is causing an issue.

import { Provider} from 'react-intl-redux';

<Provider store={store}>
    <Router routes={routes} history={browserHistory}/>
  </Provider>,

thanks

Bug: use of direct export from reference (React Native)

You use a weird way to export components from index.js. I think it is illegal but in any case, on React Native it creates an error because the import gets referenced relative to the react module and not relative to the react-intl-redux module.

You use

export IntlProvider from './components/IntlProvider'
export Provider from './components/Provider'

You should use

import IntlProvider from './components/IntlProvider'
import Provider from './components/Provider'

export ( IntlProvider, Provider }

Usecases for integrating with Redux

Hi @ratson, this is more of a question for the docs than an issue, so feel free to close it if not relevant. I am trying to add internationalization to a react-redux app, and wondering what usecases would make it ideal for integrating with redux (rather than just react by default)?

So, I am curious, what kind of usecases are people using this binding for, where it helps to have intl state in the store?

Thank you!

dispatch function is called on other actions every time updateIntl is dispatched

I have a redux action that when it's dispatched fetches data from a external service. In the response I get from the backend. I Use a countrycode attribute and pass that as the argument as the locale argument.

fetch(`/api/article/${id}`)
                .then(response => response.json())
                .then((json) => {
                    dispatch(
                        updateIntl({
                            locale: locales[json.countryCode],
                            messages: formatLocaleObject(json.countryCode),
                        }),
                    )
                    dispatch(saveSettings(json.settings))
                    dispatch(saveData(json.eta))
                })
        })

When the pageloads I dispatch an action that fetches an article. I use the country code I get from the response as the arugment to update the right locale. I expect it to be called once But When I dispatch updateIntl It dispatches the same action again that is used to fetch an article. Casiung unesseray bandwidth and pageload time.

Most dependencies should be peer dependencies

There is a React runtime validation error when importing react-redux twice that is caused by react-intl-redux not using peerDependencies.

reduxjs/react-redux#534

As far as I can see, there is no good reason to not make all the package.json "dependencies" as "peerDependencies" except for the "warning" package. It just means users will have more freedom in importing these packages themselves.

How to set a different locale?

I see that if I pass '1000' as a value for the FormattedNumber component, it's correctly formatted as '1,000' (so the integration works!). But when I try to set a locale, as in

It doesn't seem to consider italian locale: it should output '1.000', but it remains always as '1,000' (dot instead of a comma).
Thanks.

2.0.1: Not re-rendering anymore after updating locale

Upgraded to 2.0.1 yesterday and although the @@intl/UPDATE action is triggered when calling updateIntl(...) the Provider component is not re-rendered anymore. Had to revert to 2.0.0. Anyone else experiencing the same thing? FYI I'm using the <Provider> component from react-intl-redux.

Problem with connect react-redux

Problem with connect react-redux, not changed locale if use connect. Connect block props to injectIntl
1)container component
Снимок
2)presentational component
Снимок

After delete this code connect good work, but this bad idea

Split the multi languages example

Hi,
can you divide the multilingual example in separate files so that it becomes clearer what, and especially how to do it right, if you change the language of the whole application over a child component. I tried to outsource the component SelectLocale unfortunately I get the error

./src/components/SwitchLocale/index.js
  Line 12:  'store' is not defined  no-undef

Dispatch undefined

In the docs this is the code used to update the store:

dispatch(updateIntl({
  locale,
  messages,
}))

When doing this I'm getting the error:
Uncaught ReferenceError: dispatch is not defined

FormattedMessage in a connected component

I probably am missing something but is FormattedMessage supposed to work from a connected component?

I took this example https://github.com/ratson/react-intl-redux/blob/master/examples/multiple-languages/src/index.js and modified it like so:

  1. Moved FormattedMessage part into a separate component:
class Sample extends React.Component {
    render() {
        return(
            <p>
                <FormattedMessage id="app.greeting" defaultMessage="Hello!" />
            </p>
        );
    }
}
const SampleConnected = connect()(Sample);
  1. Root app now looks like this:
<Provider store={store}>
                <IntlProvider>
                    <div>
                        <SampleConnected/>
                        <p>
                            <button onClick={this.handleLoadlLocales}>
                                Local locales
                            </button>{' '}
                            <SwitchLocale />
                        </p>
                        <DevTools />
                    </div>
                </IntlProvider>
            </Provider>

...and I couldn't get locale switching to work with this code (the action dispatches normally):

selection_055

If I use a non-connected component:

<Provider store={store}>
                <IntlProvider>
                    <div>
                        <Sample/>
                        <p>
                            <button onClick={this.handleLoadlLocales}>
                                Local locales
                            </button>{' '}
                            <SwitchLocale />
                        </p>
                        <DevTools />
                    </div>
                </IntlProvider>
            </Provider>

locale switch works fine:

selection_056

Server Render?

Pleaes, answer me, how to create server-render for this module?
In my initialState on server I receive empty reducer data, but on client I receive normal reducer data for react-intl-redux.
Can anyone give me example how to make it correct?

License?

Hello, I cannot find a LICENSE file in the repository. npm says this has MIT license. Could you explicitly add a LICENSE file? Thanks!

Support for react-intl ^6.0.0

Good day

It would be great if this package supports react-intl ^6.0.0. Current support is for react-intl@"^2.2.2 || ^3.0.0 || ^4.0.0 || ^5.0.0"

Thanks and regards
Nate

Missing message: "app.greeting" for locale: "en"

First of all I've created langs.js file which wraps:

export const enData = {
    intl: {
        locale: 'en',
        messages: {
            'app.greeting': 'Hello!'
        }
    }
};
export const azData = {
    intl: {
        locale: 'az',
        messages: {
            'app.greeting': 'Salam!'
        }
    }
};
export const ruData = {
    intl: {
        locale: 'ru',
        messages: {
            'app.greeting': 'Привет!'
        }
    }
};

And of course an app.js file which wraps:

import {azData, ruData, enData} from '../../data/langs';
import {addLocaleData, FormattedMessage} from 'react-intl';

addLocaleData([ azData, ruData, enData ]);

import reducers from './reducers';
import routes from "./routes";

const reducer = combineReducers({
    ...reducers,
    intl: intlReducer
});

const store = createStore(reducer);

ReactDOM.render(
    <Provider store={store}>
        <IntlProvider>
            <Router history={hashHistory} routes={routes}/>
        </IntlProvider>
    </Provider>,
    app
);

And I'm getting the error:

[React Intl] Missing message: "app.greeting" for locale: "en"
[React Intl] Cannot format message: "app.greeting", using message id as fallback.

I don't want to set the default language. I wanna to stay the en as a default.
What is the problem???

Published npm package has old transpiled code for IntlProvider

The transpiled code in the currently published version on npm (2.0.1) is missing this change to IntlProvider from 2.0.0:

Use locale as key for IntlProvider by default

Instead it has this (in lib/components/IntlProvider.js, line 12) :

function defaultSelector(state) {
  return state.intl;
}

However, src/components/IntlProvider.js has the most recent code so I'm not sure what happened.
Looks like it will need to be re-published.

Calling dispatch updateIntl results in error "Missing locale data for locale"

In a child component I have passed into props the dispatch. I call it like so...

this.props.dispatch(updateIntl({
                eventKey,
                newmessages
            }));

...but this results in the following error, even though eventKey and newmessages have the correct values.

[React Intl] Missing locale data for locale: "undefined". Using default locale: "en" as fallback.

Here's the complete code..

index.js

import {addLocaleData, FormattedMessage} from 'react-intl'
import {createStore, combineReducers} from 'redux'
import {IntlProvider, intlReducer} from 'react-intl-redux'
import {Provider} from 'react-redux'
import itLocaleData from 'react-intl/locale-data/it'
import jaLocaleData from 'react-intl/locale-data/ja'
import React from 'react'
import ReactDOM from 'react-dom'

import LanguageSelector from './LanguageSelector';

const languageDetected = navigator.language.split('-')[0] || 'en';

export const translationMessages = {
    en: {
        'app.greeting': 'Hello!',
    },
    ja: {
        'app.greeting': 'こんにちは!',
    },
    it: {
        'app.greeting': 'Ciao!',
    }
};

// check if we have translations for the language detected, if not default to english
const languageMatched = (typeof translationMessages[languageDetected] !== 'undefined') ? languageDetected : 'en';

addLocaleData([
    ...itLocaleData,
    ...jaLocaleData,
])

const reducer = combineReducers({
    intl: intlReducer,
})
const initialState = {
    intl: {
        defaultLocale: 'en',
        locale: languageMatched,
        messages: translationMessages[languageMatched],
    },
}


const store = createStore(reducer, initialState)

const App = () => (
    <Provider store={store}>
        <IntlProvider>
            <div>
                <FormattedMessage id="app.greeting" defaultMessage="Intl locale error" /> <br/>
                Browser language: {languageDetected} <br/>
                <LanguageSelector selectedItem={LanguageSelector.English} dispatch={store.dispatch}/>
            </div>
        </IntlProvider>
    </Provider>
)

const rootDiv = document.createElement('div')
document.body.appendChild(rootDiv)
ReactDOM.render(<App />, rootDiv)

LanguageSelector.js

import {Provider} from 'react-redux'
import itLocaleData from 'react-intl/locale-data/it'
import jaLocaleData from 'react-intl/locale-data/ja'
import { DropdownButton, MenuItem } from 'react-bootstrap';
import {updateIntl} from 'react-intl-redux'
import React, { Component } from 'react';
import ReactDOM from 'react-dom'

import { translationMessages } from './index';

const OPTIONS = {
    'en': {
        title: 'English'
    },
    'ja': {
        title: 'Japanese'
    },
    'it': {
        title: 'Italian'
    }
};

const English = 'en',
    Japanese = 'ja',
    Italian = 'it';

class LanguageSelector extends Component {

    static get English() {
            return English;
    }

    static get Japanese() {
        return Japanese;
    }

    static get Italian() {
        return Italian;
    }

    constructor(props, context) {
        super(props,context);

        this.state = {
            selectedItem: this.props.selectedItem
        };

        // bind custom function to this
        this.handleSelect = this.handleSelect.bind(this)
    }

    handleSelect(eventKey,event) {
        this.setState({
            selectedItem: eventKey
        });

        let newmessages = translationMessages[eventKey]
        let localstring = 'ja'
        this.props.dispatch(updateIntl({
                eventKey,
                newmessages
            }));

        console.log(eventKey);
        console.log(newmessages);

    }

    render() {
        //console.log(OPTIONS[this.state.selectedItem]);

        return (
            <DropdownButton id="lang-dropdown"
                            title={OPTIONS[this.state.selectedItem].title}
                            onSelect={this.handleSelect}>
                <MenuItem eventKey={'en'}>{OPTIONS['en'].title}</MenuItem>
                <MenuItem eventKey={'ja'}>{OPTIONS['ja'].title}</MenuItem>
            </DropdownButton>

        );


    }
}


export default LanguageSelector;

multiple-languages demo doesn't work (greeting does not update when changing locale)

Hi, it seems that the multiple-languages demo doesn't function properly.

Clicking the "local locales" button causes the locale data to be loaded into the state and the dropdown to be populated.

Selecting a language from the dropdown causes the state.intl data to update correctly.

But the greeting on the page never updates to reflect the changes.

There is an error in the console that says

index.js:2214 [React Intl] Missing locale data for locale: "it". Using default locale: "en" as fallback.

Whichever language you select, the locale data is reported as missing and it always just displays the default english text

Fails with Babel 6

With the 1.0 version and later, the Babel config has been moved to the package.json. This causes it to be published on NPM, and when building a project using this package, Babel detects the config and tries to find @babel/preset-env. On projects still using babel-preset-env, it can't find the new version, and the build breaks:

ERROR in ./node_modules/react-intl-redux/lib/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Couldn't find preset "@babel/preset-env" relative to directory "/tmp/build/node_modules/react-intl-redux"

Would it be possible to revert this config to a npmignore'd file it so it can be used with both Babel versions?
Thanks.

passing preloadedState (server-side-rendering) not properly setting the locale data on the client side

I've experienced this issue with the following versions:

  • react-intl-redux 0.4.1
  • react-intl 2.2.3
  • redux 3.6.0
  • react-router 4.1.1
  • react 15.4.2

I'm setting server side rendering and loading the messages from the json file in the server. the store is composed of defaultLocale, locale, and messages. When I send the request for the first page, I see the translated data, no warning, it works properly.

However, on the client-side, it re-renders the page to the default locale. I was passing the preloadedState as specified in the redux documentation, so I got confused. I was also seeing the following warning client-side: [React Intl] Missing locale data for locale: "pt". Using default locale: "en" as fallback..

After some trial and error, I found why I was getting that: the locale defaults from react-intl weren't being loaded. So I added them in the client-side bootstrapping:

const locale = preloadedState.intl.locale || 'en'
const localeData = require('react-intl/locale-data/' + locale)
addLocaleData(localeData)

I don't know if this the recommended way to do it, but it seems to me that the store should have taken care of that, specifically when a locale is set/updated (that counts for language change as well), the locale-data should be loaded to prevent that "flash of unnecessary warnings".

Unless I haven't used the proper API. Still, I find it weird that the warning only happens in the client-side (server-side was rendering warning-free).

Testing strategy documentation

The react-intl project has a test helper for enzyme in order to test components and assertions on values of <FormattedMessage />.

Since your library adds redux into the mix, the test helper mountWithIntl function doesn't work - failing with:

Invariant Violation: Could not find "store" in either the context or props of "Connect(Control)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Control)".

Could this be modified to work with react-intl-redux?

Follow semver for breaking changes

In many of the recent releases of this module, breaking changes have been introduced with a minor version change. As is conventional for the JavaScript ecosystem (particularly for those who are installing react-intl-redux using npm) it would be helpful to introduce these changes along with a major version bump. Without doing so, it causes some headaches for folks who are using this module by introducing unexpected bugs, breaking builds, and hassle.

I'm hoping you might consider using Semantic Versioning going forward to help alleviate this issue. Thank you for considering and thank you for sharing your work! ❤️

Calling updateIntl not refreshing messages and loses locale data

I'm dispatching action updateIntl action inside other Thunk action and it correctly updates the redux state but none of the components wrapped in injectIntl or context base components get new locale. Everything just displays placholders and getting bunch of [React Intl] Missing locale data for locale: "xx". Using default locale: "yy" as fallback. errors in the console.

Inside components' injected props intl still contains old locale data (from before dispatching an action) even though they are render after the redux state is updated with new locale data.

Is there some bug with this or do I need to do something else than just dispatching an action so my components get updated locale data?

<IntlProvider> needs to exist in the component ancestry

Running into this issue while trying to use react-intl-redux with react router 4

server.js

import { Provider } from 'react-intl-redux'
import { StaticRouter } from 'react-router-dom'

const routerContext = {}
const htmlContent = renderToString(
    <Provider store={store}>
      <StaticRouter location={ctx.url} context={routerContext}>
        <App />
      </StaticRouter>
    </Provider>,
)

store.js

/* @flow */

import { routerMiddleware } from 'react-router-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import axios from 'axios'
import logger from '../utils/logger'

import type { Store } from '../types'
import rootReducer from './reducers'

export default (history: Object, initialState: Object = {}): Store => {
  const middlewares = [
    thunk.withExtraArgument(axios),
    routerMiddleware(history)
  ]

  const enhancers = [
    applyMiddleware(...middlewares),
    __DEV__ && typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ?
      window.devToolsExtension() : f => f
  ]

  const store: Store = createStore(rootReducer, initialState, compose(...enhancers))
  console.log('s', store)

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('./reducers', () => {
      try {
        const nextReducer = require('./reducers').default

        store.replaceReducer(nextReducer)
      } catch (error) {
        logger.error(`==> Reducer hot reloading error ${error}`)
      }
    })
  }

  return store
}

reducers.js

import { combineReducers } from 'redux'
import { routerReducer as router } from 'react-router-redux'
import { intlReducer } from 'react-intl-redux'

import home from '../containers/Home/reducer'
import userInfo from '../containers/UserInfo/reducer'

export default combineReducers({
  home,
  userInfo,
  router,
  intl: intlReducer
})

component

import React from 'react'
import { Link } from 'react-router-dom'
import { FormattedNumber, FormattedMessage, FormattedRelative } from 'react-intl'
import { IntlProvider } from 'react-intl-redux'

import styles from './styles.css'

type User = {
  id: string,
  name: string
};

type Props = Array<User>;

const UserList = ({ list }: Props) => (
  <div className={styles.UserList}>
    <h4>User List</h4>
    <ul>
      {list.map(user => (
        <li key={user.id}>
          <Link to={`/UserInfo/${user.id}`}>{user.name}</Link>
        </li>
      ))}
    </ul>
    <p>
      <small>
        <FormattedMessage
          id="posted"
          defaultMessage="posted {ago}"
          values={{
            ago: <FormattedRelative value={new Date()} />
          }}
        />
        <IntlProvider>
          <FormattedNumber value={1000} />
        </IntlProvider>
      </small>
    </p>
  </div>
)

UserList.defaultProps = {
  list: [
    {
      id: '1',
      name: 'John Galt'
    }
  ]
}

export default UserList

If I wrap all Formatted<xyz> inside IntlProvider in the component, app works fine. Without that, it fails with Invariant Violation: [React Intl] Could not find required intl object. <IntlProvider> needs to exist in the component ancestry error.

My understanding was that wrapping the App at server.js will suffice. What am I missing? I'm using this boilerplate: https://github.com/wellyshen/react-cool-starter

Usage with TypeScript

I'm trying to figure out how to use react-intl-redux with TypeScript.

I've tried this:

import { combineReducers, AnyAction } from "redux";
import { intlReducer, IntlState } from "react-intl-redux";

export type AppState = {
  intl: IntlState;
};

export type AppAction = AnyAction;

export default combineReducers<AppState>({
  intl: intlReducer
});

But I've got a warning:

Argument of type '{ intl: (state: IntlState, action: IntlAction) => IntlState; }' is not assignable to parameter of type 'ReducersMapObject<AppState, AnyAction>'.
Types of property 'intl' are incompatible.
Type '(state: IntlState, action: IntlAction) => IntlState' is not assignable to type 'Reducer<IntlState, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'IntlState | undefined' is not assignable to type 'IntlState'.
Type 'undefined' is not assignable to type 'IntlState'.
(alias) function intlReducer(state: IntlState, action: IntlAction): IntlState
import intlReducer

Could you please help me out about this?

Performance issue with immutablejs

I'm adding react-intl-redux with immutableJS to my project. There's an example of how to do that here, which is awesome: https://github.com/ratson/react-intl-redux/blob/master/test/immutable.spec.js

I am however concerned about how (in the example) intlSelector calls .toJS() on the entire i18n state every time something/anything in the redux store changes. This seems horrible for performance, especially if I have a large app with both frequent redux events and lots of i18n'd texts.

Am I misinterpreting this? Any suggestions?

how to dispatch updateIntl correctly?

I am building my first redux application and use react-intl-redux for translations.
I want to use the language of the browser as a default locale and offer buttons to switch the language.

So i have two questions:

1. Where do I best read the browser language and set the locale accordingly?

My Application has the following structure
src/actions/index.js, src/reducers/index.js, src/stores/index.js
So what works for me now is in stores/index.js:

/* localisation */
import de from '../assets/locales/de.json'
import en from '../assets/locales/en.json'

const possibleLanguage = (navigator.languages && navigator.languages[0]) || navigator.language || navigator.userLanguage
const stripRegionCode = possibleLanguage.toLowerCase().split(/[_-]+/)[0]
const locale = stripRegionCode || possibleLanguage || 'en'
const messages = { 'en': en, 'de': de }

const initialIntlState = {
  intl: {
    defaultLocale: locale,
    locale: locale,
    messages: messages[locale]
  }
}

Is this a good idea?

and 2. how do i dispatch updateIntl when a button is clicked?**

In my src/modules/App.js I would like to offer a button to switch languages:

import en from '../assets/locales/en.json'
...
handleClick () {
  const locale = 'en'
  const messages = en
  store.dispatch(updateIntl({
    locale,
    messages
  }))
}

But now I get the following error: 'store' is not defined

So am I dispatching the action at the wrong place / in the wrong manner?

Maybe this is of importance:
In my src/modules/AppContainer i use mapDispatchToProps like this:

const mapDispatchToProps = dispatch => (
  bindActionCreators(actions, dispatch)
)

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AppContainer)

npm run build fails to minify

I'm using server-side rendering with Create React App.

When I try to create a build, it shows following error, please help!

xxxxxxx226:trunk xxxxxxxxxxxxxx$ npm run build

> [email protected] build /Users/xxxxxxxxxxxxxx/xxxxxxxxx/dev/xxxxxxxxx.react/trunk
> npm run build-css && react-scripts build


> [email protected] build-css /Users/xxxxxxxxxxxxxx/xxxxxxxxx/dev/xxxxxxxxx.react/trunk
> node-sass-chokidar src/assets/ -o src/assets/

Rendering Complete, saving .css file...
Wrote CSS to /Users/xxxxxxxxxxxxxx/xxxxxxxxx/dev/xxxxxxxxx.react/trunk/src/assets/scss/app.css
Wrote 1 CSS files to /Users/xxxxxxxxxxxxxx/xxxxxxxxx/dev/xxxxxxxxx.react/trunk/src/assets/
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file: 

 	./node_modules/redux-lang/src/actions.js:3 

Read more here: http://bit.ly/2tRViJ9


npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: `npm run build-css && react-scripts build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] build script 'npm run build-css && react-scripts build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the xxxxxxxxx-React-PWA-App package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run build-css && react-scripts build
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs xxxxxxxxx-React-PWA-App
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls xxxxxxxxx-React-PWA-App
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/xxxxxxxxxxxxxx/xxxxxxxxx/dev/xxxxxxxxx.react/trunk/npm-debug.log

Thanks in Advance, hoping to get a solution asap.

react-intl version 3

Hi, are there any plans to update react-intl-redux to react-intl version 3 and maybe typescript?

Would a PR be welcomed?

Nested object syntax for translation objects?

Hi,

Sorry if this is not specific to react-int-redux, but what is it possible to have nested messages within the messages key? I'm getting annoyed at only seeing app.greetings examples.

How most examples are:

const messages = {
  local: 'en-US',
  messages: {
    'app.greetings': 'Hello, world!'
  },
};

...

<FormattedMessage id='profile.greetings' />

I would like to nest the messages so it would be easier to scale like this:

const messages = {
  local: 'en-US',
  messages: {
    views: {
      'profile.greetings': 'Hello, world!'
    },
    shared: {
      'app.greetings': 'Hello, world!'
    }
  },
};

...

<FormattedMessage id={????} />
// is it possible to put an id into FormattedMessage that would work?
// views.profile.greetings doesn't work, for example.

Thanks for any help. I'm new to react-intl in general

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.