react-admin: translate doesn't work
I am using admin on rest 1.3.1 and I am reading at this documentation :
https://marmelab.com/admin-on-rest/Translation.html#translation-messages
It says that you can import a translate method like so:
// in src/MyHelloButton.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class MyHelloButton {
render() {
const { translate } = this.context;
return <button>{translate('myroot.hello.world')}</button>;
}
}
MyHelloButton.contextTypes = {
translate: PropTypes.func,
};
I have a <IntlProvider /> wrapping my react app and messages are fully loaded but:
- Using
translatethrow error :
Warning: Failed context type: The context
translateis marked as required ingetContext(MyHelloButton), but its value isundefined. in getContext(MyHelloButton) (created by HomePage)
I have read at the react-intl documentation here https://github.com/yahoo/react-intl/wiki/API#injectintl and they provide a HoC injectIntl that can be used to retrieve messages.
This is how I fixed translate.js with injectIntl:
import React from 'react';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
export default (Component) => {
function TranslateComponent(props) {
const { intl, ...rest } = props;
return (
<Component {...rest} translate={(id) => intl.formatMessage({ id })} />
);
}
return compose(
connect(),
injectIntl,
)(TranslateComponent)
}
I am using react-intl 2.4.0.
- Why did AOR added such method ?
- Which one I should use ?
- It’s a shame to only use translate if we can’t access formatDate and other helpers so I think
injectIntlshould be use.
Also if anybody know why I have this error, thanks:!
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 27 (27 by maintainers)
@fzaninotto , I’ve just wrote the following adapter for v2 and that’s the proof
react-admincan support bothpolyglotto supportreact-intlwithout any additional maintenance cost.I use it over the original
TranslationProvider, this way I don’t need to change anything else in thera-core.That’s just a demo to be improved.
I know we have been on that topic before but we are replacing polyglot and we will proceed to
i18ntranslation.If you want to have both compatibility just say it and I can spend time trying to merge that for the rest of the community.
Otherwise we are happy to use this on our fork.
I guess so but a few change:
Correct me if I am wrong but this will serve the context twice (and probably duplicate) ?