I'm creating a node module for React just to try myself out and learn more. But I'm facing a problem. I want to make this module without any dependencies (except React) but I also want to have I18n in my module. I have started out like with this file structure:
src
|- Components
| |- myComponent.jsx
|
|- I18n
| |- en-us.js
| |- sv-se.js
|
|- index.jsx
So I want to use the I18n js files depending on which language the user calls to the module. Here are my current files:
index.jsx:
import React from 'react';
import Component from './Components/component';
class MyNewModule extends React.Component {
constructor(props) {
super(props);
this.state = {
greetings: [],
};
}
componentDidMount() {
this.setState({ greetings: [
'Hola',
'Como estas?',
'Como te llamas?',
] }); // Will use props later so user can send to module
}
render() {
return (
<Component greetings={this.state.greetings} locale={this.props.locale} />
);
}
}
export default MyNewModule;
myComponent.jsx:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
greetings: [],
};
this.getGreetings = this.getGreetings.bind(this);
}
componentDidMount() {
this.getGreetings();
}
getGreetings() {
let greetings;
if (props.greetings && props.greetings.length) {
greetings = props.greetings;
} else {
greetings = []; // HERE I WANT TO FETCH GREETINGS FROM FILE BY props.locale
}
this.setState({ greetings });
}
render() {
return (
<div>
{this.state.greetings.map((g, i) => {
return (
<div key={i}>
{g}
</div>
);
})}
</div>
);
}
}
export default MyComponent;
en-us.js:
function Lang() {
return {
greetings: [
'Hello',
'How are you?',
'What is your name?',
],
};
}
export default Lang;
sv-se.js
function Lang() {
return {
greetings: [
'Hej',
'Hur mår du?',
'Vad heter du?',
],
};
}
export default Lang;
As you can see I want to basically fetch the greetings from the corrent language file, depending on which locale the user use as property.
I have tried finding a good way to do this, and the only way I have found is to use require
as stated in Dynamically import language json file for react / react-intl but I feel that there might be a better and more "reacty" way to do this.
Any suggestions?
EDIT 1:
After suggestion from @Ozan Manav I changed the language files to use
function Lang() {
greetings: [
'Hello',
'How are you?',
'What is your name?',
],
}
and call it by using:
greetings = require(`./I18n/${this.props.locale}.js`).Lang.greetings;
but I would still like to not have to use require
if possible.