Understanding interpolation in JSX
Day 9 of #100daysofcode
Today we’ll learn about interpolation in JSX. Our initial code will be
We have our div in rootElement
, followed by a function component that receives text as props and returns null. Following that, you can see that we have an element variable that takes react.fragment (<></>)
. Inside that, we’re utilizing our function component, which takes our text and counts the characters in it, displaying the output as something like :
The element is then rendered. We must now write code in our function component. That will be :
You can see in the function CharacterCount
that we have a JSX syntax <div>
that takes JavaScript syntax with the help of in that we used backtext ``
which allows us to use our prop text after that we are using a ternary operator which checks whether the input text has length or not. If it does, we will display the length of the content in a strong tag; otherwise, we will display “NO”. Finally, we have the string. When we execute our code, we should get something like this.
This is a simple code, but when you understand it, you will notice the interpolation. Let us examine it.
First, we have our HTML code, which continues until script tag
, after which our JavaScript code begins until div
, with div tag
JSX code begins, but right after that our JavaScript code begins with, which continues until strong tag
, with strong tag
JSX code begins, inside that strong tag
you can see JavaScript code, and JSX code ends with closing strong tag
. then JavaScript code begins until the closing div tag
, then JavaScript code resumes until our react.fragment
, which begins our JSX code. With< />
, the JSX code finishes and the JavaScript code begins. Then there’s our HTML code.
As you can see, the code is basic, but the interpolation is rather complex. We can use JSX code more successfully if we understand interpolation.
That’s all for now.
If you found this useful, please follow me on Twitter @Hxrshxd for updates.