I’m reading the react documentation and on the "props" section they have a solution that takes a size prop and pass it inside the if statement’s condition. Why don’t we have "size" inside curly braces here? Shouldn’t the props be inside curly braces according to JSX? I’m pretty new to React and JSX.
function Avatar({ person, size }) {
let thumbnailSize = 's';
if (size > 90) {
thumbnailSize = 'b';
}
return (
<img
className="avatar"
src={getImageUrl(person, thumbnailSize)}
alt={person.name}
width={size}
height={size}
/>
);
}
2
Answers
In JSX, when you are using curly braces {}, it is used for embedding JavaScript expressions. In the case of the Avatar component you provided, the size prop is not inside curly braces because it is being used as a variable directly in the JSX markup.
The JSX syntax allows you to use curly braces for embedding JavaScript expressions when you need to evaluate or reference a JavaScript variable, expression, or function. However, not every use of a prop or variable in JSX requires curly braces.
In your example:
Here, width={size} and height={size} are using the size prop directly in JSX, and it doesn’t need to be wrapped in curly braces because it’s a simple variable reference.
On the other hand, if you had something more complex like conditional rendering or a JavaScript expression, then you would use curly braces.
For example:
In the above case, the width and height values are determined by a JavaScript expression (size > 90 ? size : 90), so they are wrapped in curly braces.
In summary, you use curly braces {} in JSX when you need to embed JavaScript expressions, but for simple variable references or prop values, you can use them directly without curly braces.
That’s simple, you are not using it in JSX.
JSX returns HTML in which you can use your variables by putting them in curly braces, however you are using it in a function.
Maybe you are confused since size is also in curly braces in parameters ?
If that’s so then that’s just object destructuring.
This is example of object destructuring:
In short JSX is everything in return statement, but before that it’s just javascript/typescript whatever you are using.