How to use JS in JSX
To add logic for rendering components in React, we often need to use plain JavaScript within JSX. This is done by enclosing the JavaScript code in curly brackets . It’s important to note that only expressions are allowed within these brackets, not statements.
const App = () => {
return (
<>
<h1>My name is {const name = "Seth"}</h1>
</>
);
}
The above code is invalid.
You might think {const name = "Seth"}
is valid JavaScript within JSX. However, this code block is not valid because it’s a statement—specifically, an initialization of name
. We can’t write statements inside curly brackets in JSX; only expressions are allowed.
We can make a few changes to the above code block to make it valid:
const App = () => {
return (
const name = "Seth";
<>
<h1>My name is {name}</h1>
</>
);
}
We initialized the value of name
outside the return block and used the variable name
inside curly brackets. The assigned value is "Seth"
. This makes it a valid expression.
Now that we’ve learned how to write code in React, let’s explore its fundamental concepts – the building blocks of React applications.