Junior
What is not allowed to be written in JavaScript code within JSX?
sobes.tech AI
Answer from AI
The following constructions are not allowed:
- Assignment operators (except inside attributes where a value is assigned).
- Ternary operator without explicit return value (
?:). - Loops (
for,while,do/while) without being wrapped in a function that returns JSX elements. if/elsestatements without being wrapped in a function that returns JSX elements, or without using a ternary operator.- Code blocks (
{}) without explicit JSX element return (e.g., just variable declarations). - Nested comments
// inside JSXor/* inside JSX */, except comments after operators or between attributes/elements.
It is permissible to use:
- Expressions that return values (variables, functions, method calls).
- Logical operators
&&and||. - Ternary operator
? :. - Objects and arrays (if they are rendered as a list or element).
- Array method calls (
map,filter, etc.) returning JSX elements. - Functions returning JSX elements.
Example:
// Not allowed
const element = <p>
let x = 10; // Assignment
x++; // Increment
</p>;
// Not allowed
const element = <p>
if (condition) { // if statement
return 'True';
} else {
return 'False';
}
</p>;
// Allowed with functions
const renderContent = (condition) => {
if (condition) {
return <p>'True'</p>;
} else {
return <p>'False'</p>;
}
};
const element = <div>{renderContent(true)}</div>;
// Allowed with ternary
const element = <p>{condition ? 'True' : 'False'}</p>;
// Allowed with &&
const element = <div>{condition && <p>Visible</p>}</div>;
// Allowed with map
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
const element = <ul>{listItems}</ul>;