1

I have a JSON translation file like below

"results":{
  "email-notification": "You have n mails"
}

where "n" will be a dynamic number. If 10 mails, I need to show "You have 10 mails". If 15 mails, I need to show "You have 15 mails".

How do I do this in ReactJS?

I know, in AngularJS, we can do it like below

<span ng-bind-html="results.email-notification|translate:mailCount"></span>

and in JSON

"results":{
  "email-notification": "You have {{mailCount}} mails"
}

where mailCount is the number of mails.

How do I do the same thing in ReactJS?

The below given is the JSX file

import React, {Component} from 'react';

import jsonData from "../../../public/translation/results.json";

class Results extends Component {

  var mailCount = 10;

  render() {
    return(
        <div className="results">
            <span className="result">{jsonData.results['email-notification']}</span>
        </div>
    );
  }
}

export default Results

Suppose the mailCount is 10. How do I display it?

Jeff
  • 235
  • 6
  • 16
  • Could you provide some code of what you've tried so far? It's difficult to tell what stage you're at in your debug; for all I can tell you may need anything from a full component to a fragment of JSX. – Ben Hare Jan 17 '17 at 23:28
  • I have added the JSX in my question. – Jeff Jan 17 '17 at 23:40

1 Answers1

0

Looking at this response JavaScript equivalent to printf/string.format

I changed it to a method

function translate(str, ...params) {
  if (str) {
    return str.replace(/{(\d+)}/g, function(match, number) {
      return typeof params[number] != 'undefined'
        ? params[number]
        : match
      ;
    });
  }
}

so you can use it with structures like this

const results = {
  'email-notification': 'You have {0}/{1} mails'
};

and then inside JSX

<div>
  {translate(results['email-notification'], 'Param1', 'Param2')}
</div>
Community
  • 1
  • 1
iurii
  • 4,142
  • 2
  • 23
  • 28