React js and laravel localization strings?

I recently started responding to React js and they started to like it.

There is one logic with which I am stuck.

My site is multilingual and I have problems displaying strings.

So, I was thinking of placing an attribute data-translatefor id or classes, but still not suitable.

This is just a basic example of my logic.

Js reaction

var counter =  document.getElementById('counter').getAttribute('data-translate');

var Timer = React.createClass({


  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  componentWillUnmount: function() {
    clearInterval(this.interval);
  },
  render: function() {
    return (
      <div className={this.translate}>{counter} {this.state.secondsElapsed}</div>
    );
  }
});



React.renderComponent(
    <Timer />,
    document.getElementById('counter')
  );

HTML

<div id="counter" data-translate="{{ trans('stream.counter') }}"></div>

So itโ€™s not a good idea.

Can someone give me a hint?

+4
source share
2 answers

You want to convert your translation files to JSON and use the client-side translation function.

For example, the image you created looks something like this:

var translations = {"en":{"stream":{"counter":"counter"}}};

trans :

function trans(key){
  var keys = key.split(".");
  var lang = navigator.language.split("-");
  return lang.concat(keys).reduce(function(o, k){
    var next = o[k];
    if (next) {
      console.error('No translation found for ' + key, new Error().stack);
      return {};
    }
    else {
      return next;
    }
  }, translations);
}

<div>{trans('stream.counter')}</div>
+6

API, gettext, , . , " ", .

// Data source initialised once, could be embedded in the source from the server.
var TranslationDictionary = {
    "the ticks": "les tiques",
    ...
};

// In the component:
return <div>{gettext("the ticks")}</div>;

// Then the gettext utility to join them together:
function gettext(lookup) {
    var translation = TranslationDictionary[lookup];
    if (translation) {
        return translation;
    }
    else {
        console.log("Warning: missing translation for: " + lookup);
        return lookup;
    }
}

gettext , , . , , .

0

All Articles