Interpolation in React

Hi in this post we are going to talk about interpolation, what is and how to use the interpolation in the code.

Interpolation is defined as “the insertion of something of a different nature into something else.”

For example: we are interpolating this to messages in 1 with template literals (Also called Back-Tics or String Templates or Template Strings)

const greeting = 'water'
const subject = 'World'
const message = `${greeting} ${subject}`
console.log('message --->', message)

Result:

So, everything that we put inside inside ‘ ‘ will be read as string and when we use template literals inside will be read depend of the content, for example:

This will be read as string

`Hi my name is Cristina`

This will be read as Javascript

`${variable}`

So, in React we can do interpolation using JSX

If we want to interpolate the className and the content

const element = <div className="container">Hello World</div>

Then will be like:

  const myClass = 'container'
    const children = 'Hello World'
    const element = (
      <div id="myId" className={myClass}>
        {children}
      </div>
    )

And we can see how React is interpreting this: Is creating the div element (component) and inserting props the id and the class, at the end children (content)

And when we are doing interpolation className={myClass} basically is telling Babel – just don’t do anything here, remove that curly braces { } and make that (myClass) be the property of an object. That’s why we can do

className={myClass.toUpperCase()}

Note:

We can’t make statement inside curly braces like:

Because React will interprete this as:

And this isn’t make any sense, we cannot insert a statement in a function argument.

Note: what you can do is an expression (that evaluates to a value) like use a ternary evaluation.

So React (with JSX) give us the ability to mix the markup with Javascript so we don’t have to learn any special syntax.

By Cristina Rojas.