React Components and JSX Syntax
1. Functional Components and Arrow Functions
Pattern
Syntax
Description
Use Case
Function Declaration
function Comp() {}
Traditional function syntax for components
Named exports, hoisting needed
Arrow Function
const Comp = () => {}
Modern ES6 arrow function syntax
Preferred for most components
Implicit Return
const Comp = () => (<div/>)
Single expression return without braces
Simple, presentational components
Named Export
export function Comp() {}
Export component directly
Multiple exports per file
Default Export
export default Comp
Single default export per file
One main component per file
Example: Component declaration patterns
// Function declaration
function Welcome () {
return < h1 >Hello</ h1 >;
}
// Arrow function with explicit return
const Greeting = () => {
return < h1 >Hi there</ h1 >;
};
// Arrow function with implicit return
const SimpleComp = () => (< div >Simple</ div >);
// With props destructuring
const User = ({ name , age }) => (
< div >{name}, {age}</ div >
);
2. JSX Elements and Expression Embedding (curly braces)
Feature
Syntax
Description
Example
JSX Element
<div>content</div>
HTML-like syntax in JavaScript
<h1>Title</h1>
Self-closing Tag
<Component />
Elements without children must self-close
<img src="..." />
Expression Embedding
{expression}
Execute JavaScript inside JSX
{2 + 2}
Attribute Expression
attr={value}
Dynamic attribute values
className={style}
String Literal
attr="value"
Static string attributes
type="text"
CamelCase Props
className, onClick
HTML attributes use camelCase in JSX
tabIndex, htmlFor
Comments in JSX
{/* comment */}
JavaScript-style comments in curly braces
{/* Note */}
Example: JSX expressions and embedding
const UserCard = ({ user , isOnline }) => {
const greeting = 'Welcome' ;
return (
< div className = "card" >
{ /* Dynamic content */ }
< h2 >{greeting}, {user.name}!</ h2 >
{ /* Expressions */ }
< p >Age: {user.age * 2 }</ p >
{ /* Method calls */ }
< p >{user.email. toLowerCase ()}</ p >
{ /* Dynamic attributes */ }
< img src = {user.avatar} alt = {user.name} />
< span className = {isOnline ? 'active' : 'inactive' }>
{isOnline ? 'Online' : 'Offline' }
</ span >
</ div >
);
};
Note: JSX is syntactic sugar for React.createElement(). All JSX is transformed to
JavaScript function calls during compilation.
3. Component Props and Destructuring
Pattern
Syntax
Description
Use Case
Props Object
function Comp(props) {}
Access props via object
When passing all props down
Destructuring
({ name, age }) => {}
Extract props directly in parameters
Most common pattern
Default Values
({ name = 'Guest' }) => {}
Provide fallback values
Optional props with defaults
Rest Props
({ name, ...rest }) => {}
Collect remaining props
Forwarding props to children
Nested Destructuring
({ user: { name } }) => {}
Extract nested object properties
Complex prop structures
Prop Spreading
<Comp {...props} />
Pass all props to child
Wrapper components
Example: Props destructuring patterns
// Basic destructuring with defaults
const Button = ({
text = 'Click' ,
onClick,
disabled = false
}) => (
< button onClick = {onClick} disabled = {disabled}>
{text}
</ button >
);
// Rest props and spreading
const Input = ({ label , ... inputProps }) => (
< div >
< label >{label}</ label >
< input { ... inputProps} />
</ div >
);
// Nested destructuring
const UserProfile = ({
user: { name, email, address: { city } }
}) => (
< div >
< h2 >{name}</ h2 >
< p >{email}</ p >
< p >City: {city}</ p >
</ div >
);
// Usage with explicit props
< Input label = "Email" type = "email" placeholder = "Enter email" />
4. Children Prop and Component Composition
Concept
Syntax
Description
Use Case
Children Prop
props.children
Content passed between component tags
Wrapper/container components
Children Destructuring
({ children }) => {}
Extract children directly
Cleaner component code
Multiple Children
<Comp>{child1}{child2}</Comp>
Pass multiple elements as children
Complex layouts
Render Props
children(data)
Children as function pattern
Share logic/data with children
Named Slots
header, footer props
Multiple named content areas
Flexible layouts
Composition
<A><B><C /></B></A>
Nest components for hierarchy
Building complex UIs
Example: Children and composition patterns
// Simple children wrapper
const Card = ({ children , title }) => (
< div className = "card" >
< h3 >{title}</ h3 >
< div className = "card-body" >{children}</ div >
</ div >
);
// Render props pattern
const DataProvider = ({ children , data }) => (
< div >{ children (data)}</ div >
);
// Usage
< DataProvider data = {users}>
{( users ) => (
< ul >
{users. map ( u => < li key = {u.id}>{u.name}</ li >)}
</ ul >
)}
</ DataProvider >
// Named slots pattern
const Layout = ({ header , children , footer }) => (
< div >
< header >{header}</ header >
< main >{children}</ main >
< footer >{footer}</ footer >
</ div >
);
// Composition
< Layout
header = {< Nav />}
footer = {< Footer />}
>
< Card title = "Welcome" >
< p >Content here</ p >
</ Card >
</ Layout >
5. Conditional Rendering Patterns (&&, ternary, if-else)
Pattern
Syntax
Description
Use Case
Ternary Operator
{condition ? <A/> : <B/>}
Inline if-else rendering
Two-way conditional rendering
Logical AND (&&)
{condition && <Component/>}
Render if condition is truthy
Optional content display
Logical OR (||)
{value || 'default'}
Fallback value if falsy
Default content
Nullish Coalescing
{value ?? 'default'}
Fallback only for null/undefined
Preserve falsy values (0, '')
Early Return
if (!data) return null
Guard clause before JSX
Loading/error states
IIFE Pattern
{(() => {})()}
Complex logic in JSX
Multi-statement conditionals
Element Variables
let el; if (...) el = ...
Store JSX in variables
Complex conditional logic
Example: Conditional rendering techniques
const UserStatus = ({ user , isLoading , error }) => {
// Early return for loading
if (isLoading) return < Spinner />;
// Early return for error
if (error) return < Error message = {error} />;
// Early return for no data
if ( ! user) return null ;
return (
< div >
{ /* Ternary operator */ }
{user.isPremium ? (
< PremiumBadge />
) : (
< FreeBadge />
)}
{ /* Logical AND */ }
{user.notifications && (
< NotificationBadge count = {user.notifications} />
)}
{ /* Nullish coalescing */ }
< p >Score: {user.score ?? 0 }</ p >
{ /* Multiple conditions with element variable */ }
{(() => {
if (user.role === 'admin' ) return < AdminPanel />;
if (user.role === 'moderator' ) return < ModPanel />;
return < UserPanel />;
})()}
</ div >
);
};
// Element variable pattern
const StatusDisplay = ({ status }) => {
let statusElement;
switch (status) {
case 'success' :
statusElement = < SuccessIcon />;
break ;
case 'error' :
statusElement = < ErrorIcon />;
break ;
default :
statusElement = < InfoIcon />;
}
return < div >{statusElement}</ div >;
};
Warning: Avoid using && with numbers like
{count && <Text/>} - if count is 0, it renders "0". Use
{count > 0 && <Text/>} or {!!count && <Text/>} instead.
6. JSX Fragment (<>>, React.Fragment)
Syntax
Usage
Description
Use Case
Short Syntax
<>...</>
Empty tag fragment shorthand
Group elements without wrapper
Explicit Fragment
<React.Fragment>
Full fragment component
When key prop is needed
Fragment with Key
<Fragment key={id}>
Fragment in lists with key
Mapping multiple elements
Import Fragment
import { Fragment }
Named import from React
Cleaner than React.Fragment
Example: Fragment usage patterns
import { Fragment } from 'react' ;
// Short syntax - most common
const UserInfo = () => (
<>
< h1 >User Profile</ h1 >
< p >Details</ p >
</>
);
// With key prop (required in lists)
const GlossaryList = ({ items }) => (
< dl >
{items. map ( item => (
< Fragment key = {item.id}>
< dt >{item.term}</ dt >
< dd >{item.description}</ dd >
</ Fragment >
))}
</ dl >
);
// Avoiding unnecessary divs
const Table = () => (
< table >
< tbody >
{data. map ( row => (
<>
< tr key = {row.id}>
< td >{row.name}</ td >
</ tr >
{row.details && (
< tr >
< td colSpan = "2" >{row.details}</ td >
</ tr >
)}
</>
))}
</ tbody >
</ table >
);
// Conditional multiple elements
const Form = ({ showHelp }) => (
< form >
< input type = "text" />
{showHelp && (
<>
< p >Help text</ p >
< button >Learn More</ button >
</>
)}
</ form >
);
Note: Fragments don't create extra DOM nodes, improving performance and maintaining semantic
HTML. Use <></> when no props needed, <Fragment key={...}> when mapping with keys.