Twitter LogoFacebook Logo
Interpolation
Learn how to use the React Interpolation functionality to insert dynamic values to your app.
By: King

Hello, in this tutorial, we'll learn how to insert dynamic strings into your React application.


What this mean is that instead of hard coding values in the HTML, as you saw in the Components tutorial, you can insert variables, properties or logic into the page. 

The term for this, is called Interpolation.

Interpolation

So how do we do interpolation?


Well, all you need to do is to put a pair of curly brackets in places you want to insert variables, properties, or logic.

Then when that is determined, you can just put whatever you want to in between them.

function MyFirstComponent(){

    let title = "Hello, thanks for watching!";

    return (
        <h1>{title}</h1>
    );
}

React will compute the values and then convert it into a String so it can be displayed.

In the above example, there is a variable call title. 

let title = "Hello, thanks for watching!";

Then we used interpolation to bring it into the page.

<h1>{title}</h1>

Other examples

Here is an example using an mathematical computation.

<h1>{ 1 + 1 * 200 }</h1>

Here is an example of using a function.

function MyFirstComponent(){
    function generateTWelcomMessage(name){
        return `Hello, ${name}`;
    }
    return (
        <h1>{ generateTWelcomMessage("Codeible") }</h1>
    );
}

As you can see, by doing this, our application can change throughout the course of it's lifetime.


However, if you try to change the values in real-time, the updated value does not get rendered. This is caused by how React render stuff on screen which we will talk about later.

For now, just know that we can use the { } (curly brackets) to insert stuff we want to display instead of using hard-coded values.

That's all for this tutorial. 


Sign In