In JSX, you can seamlessly integrate JavaScript expressions within your HTML-like syntax. This powerful feature allows you to dynamically render content and make your components more interactive and flexible.
To use JavaScript expressions in JSX, you enclose them in curly braces {}
. This allows you to embed variables, perform calculations, and call functions directly within your JSX.
Here’s an example demonstrating the use of JavaScript expressions inside JSX:
const lang = "English";
return (
<>
<p>I am speaking in {lang}. I am {5 + 12 + 2} years old.</p>
</>
);
Output:
I am speaking in English. I am 19 years old.
In this example:
lang
is embedded within the paragraph using curly braces.{5 + 12 + 2}
is evaluated and rendered as part of the text.Template literals provide an even more powerful way to include dynamic content within your JSX. They allow you to embed expressions and variables within a string, making it easy to construct complex strings.
Here’s an example using template literals in JSX:
const lang = "English", lang2 = "Hindi", lang3 = "Gujarati";
return (
<>
<p>I am speaking in {`${lang}, ${lang2} and ${lang3}`}.</p>
</>
);
Output:
I am speaking in English, Hindi and Gujarati.
In this example:
${lang}, ${lang2} and ${lang3}
dynamically constructs a string with multiple variables.function calculateAge(birthYear) {
const currentYear = new Date().getFullYear();
return currentYear - birthYear;
}
const birthYear = 2000;
return (
<>
<p>I am {calculateAge(birthYear)} years old.</p>
</>
);
Embedding JavaScript expressions within JSX enhances the dynamic nature of your components, making them more flexible and interactive. Use this feature to create dynamic content based on your application’s state and logic.