Learn how to create and use React components effectively
Building blocks of React applications
// components/Button.jsx
const Button = ({ text, onClick }) => {
return (
);
};
export default Button;
import Button from './components/Button';
function App() {
const handleClick = () => {
console.log('Button clicked!');
};
return (
);
}
Component properties and data passing
// components/Card.tsx
interface CardProps {
title: string;
description: string;
image?: string;
onClick?: () => void;
}
const Card: React.FC = ({
title,
description,
image,
onClick
}) => {
return (
{image &&
}
{title}
{description}
);
};
Managing state and side effects
import { useState, useEffect } from 'react';
const UserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUser = async () => {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]);
if (loading) return Loading...;
if (!user) return User not found;
return (
{user.name}
{user.email}
);
};
Building complex UIs from simple components
// Layout components
const Layout = ({ children }) => (
{children}
);
const Sidebar = ({ children }) => (
{children}
);
const Main = ({ children }) => (
{children}
);
// Usage
const App = () => (
);