React Example

React Components

Learn how to create and use React components effectively

Functional Components

Building blocks of React applications

Basic Component

// components/Button.jsx
const Button = ({ text, onClick }) => {
  return (
    
  );
};

export default Button;

Using the Component

import Button from './components/Button';

function App() {
  const handleClick = () => {
    console.log('Button clicked!');
  };

  return (
    
); }

Key Points

  • Use arrow functions for components
  • Export components as default or named exports
  • Follow PascalCase naming convention
  • Keep components focused and reusable

Props

Component properties and data passing

Props with TypeScript

// components/Card.tsx
interface CardProps {
  title: string;
  description: string;
  image?: string;
  onClick?: () => void;
}

const Card: React.FC = ({
  title,
  description,
  image,
  onClick
}) => {
  return (
    
{image && {title}}

{title}

{description}

); };

Key Points

  • Props are read-only
  • Use TypeScript for type safety
  • Make props optional with ?
  • Use prop destructuring

Hooks

Managing state and side effects

Common Hooks

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}

); };

Key Points

  • useState for local state
  • useEffect for side effects
  • Dependency array controls effect runs
  • Clean up with return function

Component Composition

Building complex UIs from simple components

Composition Example

// Layout components
const Layout = ({ children }) => (
  
{children}
); const Sidebar = ({ children }) => (
{children}
); const Main = ({ children }) => (
{children}
); // Usage const App = () => (
);

Key Points

  • Use children prop for flexibility
  • Create reusable layout components
  • Compose components for complex UIs
  • Keep components focused and single-purpose