React Upload Image With Axios

allow users to select a file, preview and upload it using a POST request to an API
import React, { useState } from 'react';
import axios from 'axios';

const FileUpload = () => {
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState(null); // Preview for image files

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];

    // Client-side validation: Check file type
    const allowedTypes = ['image/jpeg', 'image/png'];
    if (selectedFile && !allowedTypes.includes(selectedFile.type)) {
      alert('Only JPEG or PNG files are allowed');
      return;
    }

    // Client-side validation: Check file size (max 2MB)
    const maxSize = 2 * 1024 * 1024;
    if (selectedFile && selectedFile.size > maxSize) {
      alert('File size exceeds 2MB');
      return;
    }

    setFile(selectedFile);

    // Show a preview if the file is an image
    if (selectedFile && selectedFile.type.startsWith('image/')) {
      const filePreviewURL = URL.createObjectURL(selectedFile);
      setPreview(filePreviewURL);
    }
  };

  const handleFileUpload = async (event) => {
    event.preventDefault();

    if (!file) {
      alert('Please select a file before uploading.');
      return;
    }

    // Create FormData to send the file
    const formData = new FormData();
    formData.append('file', file);

    // Upload file using axios
    try {
      const response = await axios.post('https://examplebbmcode.com/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.status === 200) {
        alert('File uploaded successfully!');
      } else {
        alert('File upload failed.');
      }
    } catch (error) {
      console.error('Error uploading file:', error);
      alert('An error occurred while uploading the file.');
    }
  };

  return (
    <div>
      <h2>Upload a File</h2>
      <form onSubmit={handleFileUpload}>
        <input type="file" onChange={handleFileChange} />
        <button type="submit">Upload</button>
      </form>

      {/* Display file preview if it's an image */}
      {preview && <img src={preview} alt="Preview" style={{ width: '200px', marginTop: '10px' }} />}
    </div>
  );
};

export default FileUpload;

Error Boundary in React

Error boundaries catchs errors anywhere in their child component tree and display a fallback UI instead of crashing the whole application
// 1. Creating the Error Boundary Component
import React, { Component } from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

  // Update the state if an error is caught
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  // Log error details, e.g., to an external logging service
  componentDidCatch(error, errorInfo) {
    this.setState({ error, errorInfo });
    console.error("Error caught in Error Boundary:", error, errorInfo);
    // Here you could send error details to a remote server
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return (
        <div>
          <h1>bbmcode.com</h1>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.error && this.state.error.toString()}
            <br />
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      );
    }

    return this.props.children; 
  }
}

export default ErrorBoundary;

// 2. Using the Error Boundary
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import BuggyComponent from './BuggyComponent';

const App = () => {
  return (
    <div>
      <h1>Welcome to the Error Boundary Demo</h1>
      <ErrorBoundary>
        <BuggyComponent />
      </ErrorBoundary>
    </div>
  );
};

export default App;


// 3. Creating a Buggy Component (for testing)
import React, { useState } from 'react';

const BuggyComponent = () => {
  const [throwError, setThrowError] = useState(false);

  if (throwError) {
    throw new Error('I crashed!');
  }

  return (
    <div>
      <h2>Click the button to throw an error:</h2>
      <button onClick={() => setThrowError(true)}>Throw Error</button>
    </div>
  );
};

export default BuggyComponent;