Junior
How can JavaScript code be used within JSX?
sobes.tech AI
Answer from AI
JavaScript code in JSX can be used by enclosing it in curly braces {}.
Main methods:
- Inserting variables and expressions:
// Variable const name = 'React'; const element = <h1>Hello, {name}!</h1>; // Expression const sum = 2 + 2; const result = <p>Sum result: {sum}</p>; - Calling functions:
function formatName(user) { return user.firstName + ' ' + user.lastName; } const user = { firstName: 'Ivan', lastName: 'Petrov' }; const greeting = <h1>Hello, {formatName(user)}!</h1>; - Conditional rendering (ternary operator):
const isLoggedIn = true; const userStatus = isLoggedIn ? <p>You are logged in.</p> : <p>Please log in.</p>; - Using loops for rendering lists (usually with
map):const items = ['Item 1', 'Item 2', 'Item 3']; const listItems = items.map((item, index) => <li key={index}>{item}</li> ); const list = <ul>{listItems}</ul>; - Passing props (property values) to components:
// Passing a string <MyComponent title="Hello" /> // Passing a number <MyOtherComponent count={10} /> // Passing an object const data = { id: 1, value: 'test' }; <AnotherComponent data={data} /> // Passing a function <Button onClick={() => console.log('Button clicked')} /> - Using logical operators (
&&) for conditional rendering:const showMessage = true; const message = showMessage && <p>New message received.</p>;
It is important to remember that inside {} only expressions that return a value (string, number, JSX element, array of elements, null, undefined) can be used. Operators (if, for, while) cannot be used directly, but their functionality can be implemented using ternary operators, map loops, or by extracting logic into separate functions.