React JSX
By Saket Bhatnagar••Beginner to Intermediate
JSX
- 1JSX stands for JavaScript XML — it lets you write HTML-like code inside JavaScript
- 2JSX is used to describe what the UI should look like in React
- 3JSX looks like HTML but gets compiled to React.createElement() under the hood
- 4JSX must return only one parent element — wrap multiple elements inside a single tag like <div> or <> </>
- 5Use className instead of class — because class is a reserved word in JavaScript
- 6All tags must be properly closed — e.g. <img />, <input />, <br />
- 7JSX uses camelCase for attributes like htmlFor, onClick, tabIndex, etc.
- 8You can embed JavaScript expressions inside JSX using curly braces {}
- 9You cannot use if-else directly inside JSX — use ternary operator or conditional rendering techniques
- 10You can create reusable components and return JSX from them just like returning HTML from a function
JSX rules and examples
- 1JSX must return only one parent element
- 2
Right: return one parent element and wrap multiple elements inside it
1return <div>2 <h1>Hello</h1>3 <p>Welcome</p>4</div> - 3
Wrong: Here we are returning multiple elements
1return <h1>Hello</h1>2<p>Welcome</p> - 4Use className instead of class for CSS classes
- 5
Right: use className instead of class for CSS classes because class is a reserved word in JavaScript
1<div className='box'>Content</div> - 6
Wrong: Here we are using class instead of className for CSS classes because class is a reserved word in JavaScript
1<div class='box'>Content</div> - 7All tags must be closed properly
- 8
Right: Here we are closing the tags properly
1<img src='logo.png' /> <input type='text' /> - 9
Wrong: Here we are not closing the tags properly
1<img src='logo.png'> <input> - 10Use camelCase for attributes
- 11
Right: Here we are using camelCase for attributes because onclick and for are reserved words in JavaScript
1<label htmlFor='email'>Email</label> <button onClick={handleClick}>Click</button> - 12
Wrong: Here we are using lowercase for attributes because onclick and for are reserved words in JavaScript
1<label for='email'>Email</label> <button onclick='handleClick'>Click</button> - 13You can write JavaScript expressions using curly braces {}
- 14
Right: Here we are writing JavaScript expressions using curly braces
1<h1>{name}</h1> <p>{age > 18 ? 'Adult' : 'Minor'}</p> - 15You cannot use if-else directly inside JSX
- 16
Right: Here we are using ternary operator to conditionally render elements
1{isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>} - 17
Wrong: Here we are using if-else directly inside JSX
1if (isLoggedIn) { return <p>Welcome</p> }