Introduction to JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML but comes with the full power of JavaScript.
💡 Key Concept
JSX is not a string or HTML—it's a syntax that gets compiled to regular JavaScript function calls.
Why Use JSX?
Benefits of JSX
- Familiar Syntax: Looks like HTML, easy to read and write
- Type Safety: Can be statically analyzed with TypeScript
- Prevents Injection Attacks: Escapes values by default
- JavaScript Power: Use variables, expressions, and functions
JSX Basics
Embedding Expressions
You can embed any JavaScript expression in JSX by wrapping it in curly braces:
jsxconst name = "React Developer"; const greeting = <h1>Hello, {name}!</h1>; // You can use any expression const element = ( <div> <h1>2 + 2 = {2 + 2}</h1> <p>Current time: {new Date().toLocaleTimeString()}</p> </div> );
JSX Attributes
JSX uses camelCase for attribute names:
jsx// HTML <div class="container" tabindex="0"></div> // JSX <div className="container" tabIndex="0"></div>
Creating Components
Function Components
The modern way to create React components:
tsxfunction Welcome(props) { return <h1>Hello, {props.name}</h1>; } // Arrow function syntax const Welcome = ({ name }) => { return <h1>Hello, {name}</h1>; }; // With TypeScript interface WelcomeProps { name: string; } const Welcome: React.FC<WelcomeProps> = ({ name }) => { return <h1>Hello, {name}</h1>; };
Component Composition
Build complex UIs by composing smaller components:
tsxfunction Avatar({ user }) { return ( <img src={user.avatarUrl} alt={user.name} className="rounded-full" /> ); } function UserInfo({ user }) { return ( <div className="user-info"> <Avatar user={user} /> <div className="user-details"> <h3>{user.name}</h3> <p>{user.email}</p> </div> </div> ); } function UserCard({ user }) { return ( <div className="card"> <UserInfo user={user} /> <button>Follow</button> </div> ); }
Props and Children
Best Practices
✅ Component Best Practices
- Keep components small and focused - One component, one responsibility
- Use meaningful names - Component names should be descriptive
- Validate props - Use TypeScript or PropTypes
- Avoid deep nesting - Extract nested components
- Use composition over inheritance - Compose smaller components
Practice Exercise
Try creating a ProfileCard component that displays:
- User avatar
- User name and bio
- Social media links
- Follow button
tsxinterface User { name: string; bio: string; avatar: string; social: { twitter?: string; github?: string; }; } function ProfileCard({ user }: { user: User }) { // Your implementation here }
Next Steps
In the next lesson, we'll explore State and Hooks to make our components interactive!