-
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
-
Let’s write a React component that has some conditional logic in it to explore the interpolation characteristics of JSX syntax:
<body>
<div id="root"></div>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script type="text/babel">
function CharacterCount({ text }) {
// this is JavaScript land
return (
// inside of the brackets it's React land
<div>
{/* this is all JavaScript land */}
{`The text "${text}" has `}
{/* this is a conditional (ternary) operator */}
{/* This operator is frequently used as a shortcut for the if statement */}
{text.length ? <strong>{text.length}</strong> : 'No'}
{' characters'}
</div>
// this is JavaScript land
);
}
const element = (
<>
<CharacterCount text="Hello World" />
<CharacterCount text="" />
</>
);
ReactDOM.render(element, document.getElementById('root'));
</script>
</body>
- Inside the curly braces, it's JavaScript land, but it's limited to only expressions.
- Interpolation is not unique to React or JavaScript, we also see it in HTML when we use
script
tags orstyle
tags.
<body>
<div id="root"></div>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script type="text/babel">
function CharacterCount({ text }) {
return (
<div>
{/* this is all JavaScript land */}
{/* but it's limited to only expressions that evaluates to some value */}
{/* no loops, switch, or if statments */}
{`The text "${text}" has `}
{text.length ? <strong>{text.length}</strong> : 'No'}
{' characters'}
</div>
);
}
const element = (
<>
<CharacterCount text="Hello World" />
<CharacterCount text="" />
</>
);
ReactDOM.render(element, document.getElementById('root'));
</script>
</body>