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

[Question] Best way to translate without the component? #983

Closed
kud opened this issue Jul 7, 2017 · 10 comments
Closed

[Question] Best way to translate without the component? #983

kud opened this issue Jul 7, 2017 · 10 comments
Labels

Comments

@kud
Copy link

kud commented Jul 7, 2017

Hey,

I'd like to know what's the best way to translate without using the component.

For the moment, I do this:

import React from "react"
import PropTypes from "prop-types"
import { injectIntl, intlShape, defineMessages } from 'react-intl'

const messages = defineMessages({
  searchSearchboxPlaceholder: {
    id: 'search.searchbox.placeholder'
  }
})

class App extends React.Component {
  static propTypes = {
    intl: intlShape.isRequired
  }

  render() {
    const intl = this.props.intl

    return 
              <Search
                placeholder={intl.formatMessage(messages.searchSearchboxPlaceholder)}
              />
  }
}

export default injectIntl(App)

But it seems to be for me a bit too verbose or non-direct. It's a quite annoying to have to use definesMessages first.

Isn't possible to do a way like:

placeholder={intl.formatMessage(search.searchbox.placeholder)} or placeholder={intl.formatMessage(defineMessage(search.searchbox.placeholder))}?

@okovpashko
Copy link

@kud you can skip defineMessages and formatting will work fine. But in that case, babel-plugin-react-intl won't be able to recognize messages in your file and won't export them to your 'messages' folder.

@jejay
Copy link

jejay commented Aug 10, 2017

I have the same question and I realy don't get your answer. How can I skip defineMessages without getting the logical ReferenceError: messages is not defined. When I do intl.formatMessage("myid") instead it says Error: [React Intl] An id must be provided to format a message..

@okovpashko
Copy link

@jejay you must provide a message descriptor instead of the message id. The descriptor format is the same as for defineMessage (link)
So correct usage for your case is

intl.formatMessage({id: "myid"})

@jejay
Copy link

jejay commented Aug 10, 2017

Thank you. It was the next thing I just attempted. For me this is not obvious from the docs, maybe it should be elaborated a little bit more. So again, thank you very much @okovpashko .

@waynebloss
Copy link

waynebloss commented Nov 6, 2017

I access the child context offered by the IntlProvider in order to use react-intl outside of my JSX components. I create a component to capture the context.intl and then save that as a static variable in my own module. Then I can expose that object or wrap its function calls as I see fit.

Every time this comes up, someone warns you "to not use context" because it's semi-internal, semi-stable, experimental and/or not-recommended in React. But react-intl itself (and many other projects) need to use context. If it goes away, everything is going to break anyway - something we're all probably used to with React versioning. That's just my opinion though - I generally just do what I need to do.

Anyway, some code:

// Intl.js
import { intlShape } from 'react-intl';

/** @type {intlShape} */
var intl;

/** React component to capture the context.  */
export function IntlCapture(props, context) {
  // Other examples show this access being done in `componentWillMount`.
  // This works just fine.
  intl = context.intl;
  // Done. Just return the children to be rendered.
  return props.children;
}

IntlCapture.contextTypes = {
  intl: intlShape.isRequired
};

/** This is the wrapper for `intl` where I expose its functionality. */
class _Intl {
  t(message, values) { return intl.formatMessage(message, values); }
  // ...
  async load(locale) {
    // ... some code to fetch a locale translation file from `/locales/${locale}.json`.
  }
}
const Intl = new _Intl();
export default Intl;
// index.js
import { IntlProvider } from 'react-intl';
import Intl, {IntlCapture} from './lib/Intl';

function render() {
  const rootContainer = document.getElementById('root');
  const rootElement = (
    <IntlProvider
      locale={Intl.locale}
      defaultLocale={Intl.defaultLocale}
      messages={Intl.messages}>
      <IntlCapture>
        <ReduxProvider store={store}>
          <App />
        </ReduxProvider>
      </IntlCapture>
    </IntlProvider>
  );
  ReactDOM.render(rootElement, rootContainer);
}

Intl.load('en').then(render).catch(render);

NOTE: In the implementation of my Intl.js module above, I left out some details that you can fill in yourself. As you can see in my index.js file, there are some other Intl properties in use - namely: Intl.locale, Intl.defaultLocale and Intl.messages. These are all assigned during my Intl.load method.

See also:

#749 - String without FormattedMessage
#942 - Can we use the lib instead of the FormattedMessage component

@waynebloss
Copy link

One other note - if you make an Intl wrapper, be aware that you cannot wrap the defineMessages function from react-intl because you will lose the ability to extract messages with babel-plugin-react-intl or react-intl-cra (if you use create-react-app).

@waynebloss
Copy link

One mistake that I made - don't name your module Intl as I did in Intl.js above because it clashes with the browser global Intl object.

I wanted a short name, so I renamed it to LL which stands for Language & Locale in my project.

@bmcalees
Copy link

module.exports = injectIntl(redux.connect(mapStateToProps, mapDispatchToProps, mergeProps)((props) => { document.formatMessage = props.intl.formatMessage; return (<App {...props} />); }));

In your wrapper component you could always assign the function to the document. NOT a fan of this hack but it works.

@stale
Copy link

stale bot commented May 30, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix label May 30, 2019
@stale
Copy link

stale bot commented Jun 6, 2019

Issue was closed because of inactivity. If you think this is still a valid issue, please file a new issue with additional information.

@stale stale bot closed this as completed Jun 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants