Code Examples

Updated Nov 1, 2024

Code Examples

Learn from practical code examples showcasing common patterns and best practices.

🎯 React Patterns

Custom Hook for API Calls

import { useState, useEffect } from 'react';

export function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch(url);
        if (!response.ok) throw new Error('Failed to fetch');
        const json = await response.json();
        setData(json);
        setError(null);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}

// Usage
function UserProfile({ userId }) {
  const { data, loading, error } = useFetch(`/api/users/${userId}`);

  if (loading) return <Spinner />;
  if (error) return <Error message={error} />;
  return <div>{data.name}</div>;
}

Context Provider Pattern

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

🔥 Firebase Integration

Authentication Setup

import { initializeApp } from 'firebase/app';
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signInWithPopup,
  GoogleAuthProvider
} from 'firebase/auth';

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();

// Email/Password Sign Up
export async function signUp(email, password) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    return { user: userCredential.user, error: null };
  } catch (error) {
    return { user: null, error: error.message };
  }
}

// Google Sign In
export async function signInWithGoogle() {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    return { user: result.user, error: null };
  } catch (error) {
    return { user: null, error: error.message };
  }
}

// Sign Out
export async function signOut() {
  return auth.signOut();
}

Firestore CRUD Operations

import { getFirestore, collection, doc, getDoc, getDocs, addDoc, updateDoc, deleteDoc, query, where } from 'firebase/firestore';

const db = getFirestore();

// Create
export async function createTask(task) {
  const docRef = await addDoc(collection(db, 'tasks'), {
    ...task,
    createdAt: new Date(),
    updatedAt: new Date(),
  });
  return docRef.id;
}

// Read One
export async function getTask(taskId) {
  const docRef = doc(db, 'tasks', taskId);
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    return { id: docSnap.id, ...docSnap.data() };
  }
  return null;
}

// Read All
export async function getTasks(userId) {
  const q = query(
    collection(db, 'tasks'),
    where('userId', '==', userId)
  );
  const querySnapshot = await getDocs(q);
  return querySnapshot.docs.map(doc => ({
    id: doc.id,
    ...doc.data()
  }));
}

// Update
export async function updateTask(taskId, updates) {
  const docRef = doc(db, 'tasks', taskId);
  await updateDoc(docRef, {
    ...updates,
    updatedAt: new Date(),
  });
}

// Delete
export async function deleteTask(taskId) {
  const docRef = doc(db, 'tasks', taskId);
  await deleteDoc(docRef);
}

🎨 Tailwind CSS Patterns

Responsive Card Component

function ProductCard({ product }) {
  return (
    <div className="
      group relative overflow-hidden rounded-2xl
      bg-white dark:bg-gray-800
      shadow-lg hover:shadow-2xl
      transition-all duration-300
      transform hover:-translate-y-2
    ">
      {/* Image */}
      <div className="relative h-64 overflow-hidden">
        <img
          src={product.image}
          alt={product.name}
          className="
            w-full h-full object-cover
            group-hover:scale-110
            transition-transform duration-500
          "
        />
        <div className="
          absolute inset-0
          bg-gradient-to-t from-black/60 to-transparent
          opacity-0 group-hover:opacity-100
          transition-opacity duration-300
        ">
          <button className="
            absolute bottom-4 right-4
            bg-white text-gray-900
            px-6 py-2 rounded-full
            font-semibold
            transform translate-y-4 group-hover:translate-y-0
            transition-transform duration-300
          ">
            Quick View
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        <h3 className="text-xl font-bold mb-2 text-gray-900 dark:text-white">
          {product.name}
        </h3>
        <p className="text-gray-600 dark:text-gray-300 mb-4">
          {product.description}
        </p>
        <div className="flex items-center justify-between">
          <span className="text-2xl font-bold text-cyan-500">
            ${product.price}
          </span>
          <button className="
            bg-gradient-to-r from-cyan-500 to-teal-500
            text-white px-6 py-2 rounded-lg
            font-semibold
            hover:shadow-lg hover:scale-105
            transition-all duration-200
          ">
            Add to Cart
          </button>
        </div>
      </div>
    </div>
  );
}

Loading Skeleton

function Skeleton() {
  return (
    <div className="animate-pulse">
      <div className="h-64 bg-gray-300 dark:bg-gray-700 rounded-xl mb-4" />
      <div className="space-y-3">
        <div className="h-4 bg-gray-300 dark:bg-gray-700 rounded w-3/4" />
        <div className="h-4 bg-gray-300 dark:bg-gray-700 rounded w-1/2" />
      </div>
    </div>
  );
}

🎭 Animation Examples

Framer Motion Variants

import { motion } from 'framer-motion';

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      delayChildren: 0.3,
      staggerChildren: 0.2
    }
  }
};

const itemVariants = {
  hidden: { y: 20, opacity: 0 },
  visible: {
    y: 0,
    opacity: 1
  }
};

function AnimatedList({ items }) {
  return (
    <motion.ul
      variants={containerVariants}
      initial="hidden"
      animate="visible"
      className="space-y-4"
    >
      {items.map((item) => (
        <motion.li
          key={item.id}
          variants={itemVariants}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          className="p-4 bg-white rounded-lg shadow"
        >
          {item.text}
        </motion.li>
      ))}
    </motion.ul>
  );
}

📱 React Native Examples

Reusable Button Component

import { TouchableOpacity, Text, ActivityIndicator } from 'react-native';

function Button({
  title,
  onPress,
  loading = false,
  variant = 'primary',
  disabled = false
}) {
  const styles = {
    primary: 'bg-blue-500',
    secondary: 'bg-gray-500',
    danger: 'bg-red-500',
  };

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled || loading}
      className={`
        ${styles[variant]}
        ${disabled ? 'opacity-50' : ''}
        px-6 py-3 rounded-full
        flex-row items-center justify-center
      `}
    >
      {loading ? (
        <ActivityIndicator color="white" />
      ) : (
        <Text className="text-white font-semibold text-lg">
          {title}
        </Text>
      )}
    </TouchableOpacity>
  );
}

🔐 Protected Routes

import { Navigate } from 'react-router-dom';
import { useAuth } from './hooks/useAuth';

function ProtectedRoute({ children }) {
  const { user, loading } = useAuth();

  if (loading) {
    return <LoadingScreen />;
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return children;
}

// Usage in router
<Route
  path="/dashboard"
  element={
    <ProtectedRoute>
      <Dashboard />
    </ProtectedRoute>
  }
/>

📝 Form Validation

import { useForm } from 'react-hook-form';

function ContactForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = async (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <input
          {...register('name', {
            required: 'Name is required',
            minLength: { value: 2, message: 'Name must be at least 2 characters' }
          })}
          placeholder="Your name"
          className="w-full px-4 py-2 border rounded-lg"
        />
        {errors.name && (
          <p className="text-red-500 text-sm mt-1">{errors.name.message}</p>
        )}
      </div>

      <div>
        <input
          {...register('email', {
            required: 'Email is required',
            pattern: {
              value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
              message: 'Invalid email address'
            }
          })}
          placeholder="your@email.com"
          className="w-full px-4 py-2 border rounded-lg"
        />
        {errors.email && (
          <p className="text-red-500 text-sm mt-1">{errors.email.message}</p>
        )}
      </div>

      <button
        type="submit"
        className="w-full bg-cyan-500 text-white py-2 rounded-lg hover:bg-cyan-600"
      >
        Submit
      </button>
    </form>
  );
}

More Examples Coming Soon!

We're constantly adding new examples. Request specific examples →


← Back to Templates | View Tutorials →