1

I currently have strings being returned from a server which have variables that need to be interpolated on the front end. I'm using React and Redux and set the strings to the component's props so that they are accessed as follows:

this.props.translations['hello-message']

An example string looks like:

Hello, ${name}!

In addition, I have the user's name being returned from the server and set to props as well. How can I interpolate the string so that the user's name appears in the string and thus in the rendered React component.

I've tried use the String.prototype.replace() method in the render of the React component as follows:

let helloMessage = this.props.translations['hello-message'].replace('${name}', 'Joe');

But this returns an error of: "Uncaught TypeError: Cannot read property 'replace' of undefined". I've tried various other strategies such as functions inside componentWillReceiveProps() or creating a helper function as mentioned here: How can I construct a Template String from a regular string? all to no avail.

Community
  • 1
  • 1
parkskier
  • 43
  • 1
  • 6

1 Answers1

2

That error message means that this.props.translations['hello-message'] does not contain the value you think it does. This is likely a react issue, where your code is calling this section multiple times while it pulls data from the Redux store, and on the first call that var is not yet initialized.

As a very simple solution, try wrapping that statement with a check to see if the variable exists yet;

let helloMessage = '';
if(this.props.translations['hello-message']){
    helloMessage = this.props.translations['hello-message'].replace('${name}', 'Joe');
}
Jake Haller-Roby
  • 6,335
  • 1
  • 18
  • 31