JSX and components in React
Learn how to write JSX and create reusable components in React
- Course
- React fundamentals
- Lesson
- 3 of 9
- Level
- Beginner
- Reading time
- 25 minutes
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:
jsx
const name = "React Developer"
const greeting = <h1>Hello, {name}!</h1>
// You can use any expression
const element = (
<div>
<h1>2 + 2 = {2 + 2}</h1>
Current time: {new Date().toLocaleTimeString()}
</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:
tsx
function 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:
tsx
function Avatar({ user }) {
return <img src={user.avatarUrl} alt={user.name} className="avatar" />
}
function UserInfo({ user }) {
return (
<div className="user-info">
<Avatar user={user} />
<div className="user-details">
<h3>{user.name}</h3>
{user.email}
</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 2. Use meaningful names - Component names should be descriptive 3. Validate props - Use TypeScript or PropTypes 4. Avoid deep nesting - Extract nested components 5. 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
tsx
interface User {
name: string
bio: string
avatar: string
social: {
twitter?: string
github?: string
}
}
function ProfileCard({ user }: { user: User }) {
// Your implementation here
}Next Steps ¶
Next lesson
In the next lesson, we'll explore State and Hooks to make our components interactive!
Further reading