✅ JSX Rules & Best Practices
JSX is powerful and expressive, but it comes with specific rules and conventions that help ensure your code is valid and clean. Following best practices also improves maintainability and readability.
📏 Core JSX Rules
- Single Root Element: JSX expressions must have one parent element.
- Use
className: UseclassNameinstead ofclassto avoid conflicts with JavaScript reserved words. - Self-Closing Tags: Tags like
<img />,<br />,<input />must be self-closed. - camelCase Attributes: Use camelCase for DOM properties like
onClick,tabIndex, etc.
<div className="container">
<img src="logo.png" alt="Logo" />
</div>
💡 Use Fragments When Needed
When returning multiple elements without adding extra nodes to the DOM, use fragments:
<>
<h1>Welcome</h1>
<p>This is a React app.</p>
</>
🧼 Best Practices
- Keep JSX clean: Break complex JSX into smaller components.
- Use meaningful names: For variables and components.
- Indent properly: Use consistent spacing for better readability.
- Avoid inline styles: Prefer CSS classes or styled-components.
- Use
keyin lists: Always provide a uniquekeywhen rendering lists.
🚫 Avoid Common Mistakes
- Don’t forget to import
React(not required in React 17+ with new JSX transform). - Don’t return multiple elements without a wrapper.
- Don’t use
ifstatements inside JSX – use ternary or logical operators. - Don’t mutate state directly – always use setters like
setStateoruseState.
📚 Example of Good JSX Practice
function Welcome({ name }) {
return (
<div className="welcome-message">
<h2>Hello, {name}!</h2>
<p>Glad to see you here.</p>
</div>
);
}


