Javascript Expressions in JSX
In JSX, you can write JavaScript expressions by wrapping them in curly braces {}. For example, you can use a JavaScript variable or a function call inside JSX by enclosing it in curly braces.
const name = "John";
// Using a variable in JSX
<h1>Hello, {name}</h1>
// Using a function call in JSX
function greet(name) {
return `Hello, ${name}`;
}
<h1>{greet(name)}</h1>
Output-
Hello, John
Hello, John
Keep in mind that JSX is just a syntax sugar on top of JavaScript, so you can use any valid JavaScript expression inside JSX.
--> Template Literals
Template literals are a feature of JavaScript that allows you to create strings using a more readable and convenient syntax. They are denoted by backticks (``
) rather than single or double quotes.
In React, template literals can be used to create dynamic JSX elements. For example, you can use template literals to interpolate variables inside JSX.
const fName = "Ema";
const lName = "Shaikh";
ReactDom.render(
<>
<h1> {`my name is {fName} {lName}`} </h1>
<h1> my name is {fName} + " " + {lName} </h1>
// without backticks you need to add + and give space.
</>,
document.getElementById("root")
);
Output-
my name is Ema Shaikh
my name is Ema Shaikh
In summary, template literals in React is a useful way to insert dynamic values and expressions inside JSX using a more readable and concise syntax.