Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Create an AWS account and login to the AWS Management Console.
  2. Create an IAM user and give it necessary permissions to interact with the required AWS services.
  3. Import the AWS SDK for JavaScript into your React project using a package manager like npm or yarn.
  4. Instantiate an AWS service object in your React app using the SDK, and authenticate using the IAM user credentials.
  5. Use the service object to make API requests, such as calling the S3 API to upload a file or the DynamoDB API to read or write data.
  6. Handle any errors or returned data from the API request within your React app.

Example code to upload a file to an S3 bucket using the AWS SDK and React:

import React, { useState } from 'react';
import AWS from 'aws-sdk';

const UploadFiles = () => {
  const [file, setFile] = useState(null);

  const handleFileInputChange = (event) => {
    setFile(event.target.files[0]);
  }

  const handleFileUpload = async () => {
    const s3 = new AWS.S3();
    const fileName = file.name;
    const bucketName = 'my-bucket-name';
    const fileData = await file.arrayBuffer();
    const params = {
      Bucket: bucketName,
      Key: fileName,
      Body: fileData
    };
    s3.upload(params, (err, data) => {
      if (err) {
        console.error(`Error uploading file: ${err}`);
      } else {
        console.log(`File uploaded successfully: ${data.Location}`);
      }
    });
  }

  return (
    <div>
      <input type="file" onChange={handleFileInputChange} />
      <button onClick={handleFileUpload}>Upload file</button>
    </div>
  );
};

export default UploadFiles;