Search code examples
react-nativestring-interpolation

When to use string interpolation in React Native?


I know HOW to use string interpolation, but not sure when to use it. I have been teaching myself React Native lately, and the instructor used string interpolation on a button title. However, he didn't use it earlier in the course when he was passing a string variable into a Text tag.

Let me know if you need an example of what I am talking about.

Example:

How come this doesn't work?

<Button title='Hello my name is {myName}'/>

But this does

<Button title={`Hello my name is ${myName}`}/>

Solution

  • The { } indicate that what is contained within is a javascript expression.

    String interpolation is javascript code.

    When you do `${someText}` — React Native does not detect that this is javascript and reads it as just a string.

    When you do {`${someText}`} — React Native realises that what is inside is Javascript and it needs to treat it as such and therefore String interpolation is valid and works.