Lesson 2 - JSX

2.2 - Embedding JavaScript Expressions In JSX

Embedding JavaScript expressions directly into the HTML is one of the powerful features of React JSX. This makes it easy to integrate dynamic content and logic into your UI components and create an interactive and dynamic user interface.

Unlike traditional web development, where you need to juggle HTML, CSS, and JavaScript to implement a feature, JSX streamline the process.

You can embed a variety of JavaScript expressions within JSX as follows:

Variable: You can declare a variable like JavaScript and embed it into the HTML component. To do this, you need to include the variable with curly braces {} inside the HTML component.

For example:

function App() {
 const name = 'John';

 return (
 <>
 <h1>Hello, {name}!</h1>;
 </>
 );
}

Function: Functions are crucial components of modern software architecture. JSX allows you to define a function similar to JavaScript and embed it in the HTML element. Similar to a variable, you've to enclose the function name with curly braces {} inside the HTML element.

For example,

function App() {
 function formatName(user) {
 return user.firstName + ' ' + user.lastName;
 }
 const user = { firstName: 'John', lastName: 'Doe' };

 return (
 <>
 <h1>Hello, {formatName(user)}!</h1>;
 </>
 );
}

Conditional Expressions: Conditional expressions let you implement logic in your application. For example, you can have a condition that checks if the user logged in. JSX allows you to do that with just a few lines of code as follows:

function App() {
 const isLoggedIn = true;

 return (
 <>
 <p>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</p>
 </>
 );
}

In the example above, we used the shorted version of the if...else condition that checks the variable isLoggedIn to determine if the user logged in.