Interview question
What is JSX and how does it work? JSX क्या है और कैसे काम करता है?
Answer
JSX is a syntax extension that allows writing HTML-like code in JavaScript. It's not valid JavaScript, so it needs to be compiled to regular JavaScript function calls using Babel.
// JSX syntax
const element = (
<div className='container'>
<h1>Hello, World!</h1>
<p>This is JSX</p>
</div>
);
// Compiled to:
const element = React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', null, 'Hello, World!'),
React.createElement('p', null, 'This is JSX')
);
// JSX with variables
const name = 'John';
const age = 25;
const greeting = (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old</p>
</div>
);
// JSX with expressions
const sum = (
<div>
<p>2 + 2 = {2 + 2}</p>
<p>Name: {name.toUpperCase()}</p>
<p>Is adult: {age >= 18 ? 'Yes' : 'No'}</p>
</div>
);
// JSX with attributes
const link = <a href='https://example.com'>Click here</a>;
const image = <img src='image.jpg' alt='Image' />;
// JSX with children
const card = (
<div className='card'>
<h2>Title</h2>
<p>Content here</p>
<button>Click me</button>
</div>
);// JSX - HTML जैसा syntax JavaScript में
const element = <h1>Hello</h1>;
// Babel से compiled होता है
const element = React.createElement('h1', null, 'Hello');
// JSX में variables
const name = 'John';
const el = <p>Hello, {name}</p>;
// Expressions
const age = 25;
const status = <p>{age >= 18 ? 'Adult' : 'Minor'}</p>;Was this answer clear?