Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

Bhubaneswar, India

info@krescitus.com

+1 -800-456-478-23

Technology

Prerequisites:

Before you begin, make sure you have the following installed

Install the Amplify CLI:

Ø Go to the command prompt first check whether the Amplify CLI is Installed or not using the following command

amplify  –version

Ø If the Amplify CLI not install then Install the Amplify CLI Globally using the following command otherwise don’t run this command.

Configure the Amplify CLI:

To Configure the Amplify CLI run the following command:

When we run the command it redirects to the AWS console for sign-in

When we run the command it redirects to the AWS console for Sign In

If the User has an IAM account and also has the Access Key and Secret key then no need to create the New IAM User otherwise we create the new IAM user
After Signing in IAM User creation page if it’s not already done.
After Creating the IAM user and then get the Secret Key and Access Key ID. Press Enter to Continue and select the Region after enter it redirects to the
https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli
After that enter the access key and SecretAccessKey of the newly created user and then choose the Profile Name ad default. After that, our Amplify CLI has been configured successfully.

Set up a full-stack project:

Create a new React App:

From Our Project directory, run the following command

From the react-amplified directory, run the app by using the following command:

After running the above command our react app compiles successfully.

When we run the http://localhost:3000 our react Application looks like as default. So finally our React App was created successfully.

Initialize a new backend:

Open a new terminal. From the react-amplified directory, run:

When you initialize Amplify you’ll be prompted for some information about the app, with the option to accept recommended values:

When you initialize a new Amplify project, a few things happen:

  • It creates a top level directory called amplify that stores your backend definition. During the tutorial you’ll add capabilities such as a GraphQL API and authentication. As you add features, the amplify folder will grow with infrastructure-as-code templates that define your backend stack. Infrastructure-as-code is a best practice way to create a replicable backend stack.
  • It creates a file called aws-exports.js in the src directory that holds all the configuration for the services you create with Amplify. This is how the Amplify client is able to get the necessary information about your backend services.
  • It modifies the .gitignore file, adding some generated files to the ignore list
  • A cloud project is created for you in the AWS Amplify Console that can be accessed by running amplify console. The Console provides a list of backend environments, deep links to provisioned resources per Amplify category, status of recent deployments, and instructions on how to promote, clone, pull, and delete backend resources.

Install Amplify Libraries:

The aws-amplify package is the main library for working with Amplify Libraries in your projects:

Set up frontend:

Next, configure Amplify so it can interact with backend services.
Open src/index.js and add the following code below the last import:

And that’s all it takes to configure Amplify. As you add or remove categories and make updates to your backend configuration using the Amplify CLI, the configuration in aws-exports.js will update automatically.

Now that our React app is set up and Amplify is initialized,

Connect API and database to the app:

Now that you’ve created and configured a React app and initialized a new Amplify project, you can add a feature. The first feature you will add is an API.
The Amplify CLI supports creating and interacting with two types of API categories: REST and GraphQL.
The API you will be creating in this step is a GraphQL API using AWS AppSync (a managed GraphQL service) and the database will be Amazon DynamoDB (a NoSQL database).

Create a GraphQL API and database:

Add a GraphQL API to your app and automatically provision a database by running the following command from the root of your application directory:

The CLI should open this GraphQL schema

amplify/backend/api/myapi/schema.graphql

The schema generated is for a Todo app. You’ll notice a directive on the Todo type of @model. This directive is part of the GraphQL transform library of Amplify.

The GraphQL Transform Library provides custom directives you can use in your schema that allow you to do things like define data models, set up authentication and authorization rules, configure serverless functions as resolvers, and more.

A type decorated with the @model directive will scaffold out the database table for the type (Todo table), the schema for CRUD (create, read, update, delete) and list operations and the GraphQL resolvers needed to make everything work together.

From the command line, press enter to accept the schema and continue to the next steps.     

Deploying the API:

After that my aws-export.js updated

Now the API is live and you can start interacting with it!
The API you have deployed is for a Todo app, including operations for creating, reading, updating, deleting, and listing todos.
Next, run the following command to check Amplify’s status:

Add authentication:
The next feature you will be adding is authentication.
Authentication with Amplify:
Amplify uses Amazon Cognito as the main authentication provider. Amazon Cognito is a robust user directory service that handles user registration, authentication, account recovery & other operations. In this tutorial, you’ll learn
how to add authentication to your application using Amazon Cognito and username/password login.
Create the Authentication Services:
To add authentication to your app, run this command:

To deploy the service, run the push command:

Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command:

After Hitting Enter it redirect to the AWS amplify

Install Amplify UI:

The @aws-amplify/ui-react package includes React specific UI components you’ll use to build your app. Install it with this:


import React, { useEffect, useState } from 'react'
import { Amplify, API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'
import { listTodos } from './graphql/queries'
import { deleteTodo } from './graphql/mutations';
import { updateTodo } from './graphql/mutations';
import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';                  	
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
 
const initialState = { name: '', description: '' }
 
const App = ({ signOut, user }) => {
  const [formState, setFormState] = useState(initialState)
  const [todos, setTodos] = useState([])
 
  useEffect(() => {
    fetchTodos()
  }, [])

function setInput(key, value) {
    setFormState({ ...formState, [key]: value })
  }
 
  async function fetchTodos() {
    try {
      const todoData = await API.graphql(graphqlOperation(listTodos))
      const todos = todoData.data.listTodos.items
      setTodos(todos)
    } catch (err) { console.log('error fetching todos') }
  }
 
  async function addTodo() {
    try {
      if (!formState.name || !formState.description) return
      const todo = { ...formState }
      setTodos([...todos, todo])
      setFormState(initialState)
      await API.graphql(graphqlOperation(createTodo, {input: todo}))
    } catch (err) {
      console.log('error creating todo:', err)
    }
  }
  async function updateTodoItem(id, newName, newDescription) {
    try {
       await API.graphql(
        graphqlOperation(updateTodo, {
          input: {
            id: id, // The ID of the item to update
            name: newName, // The new name value
            description: newDescription, // The new description value
          },
        })
      );
      const updatedTodos = todos.map((todo) =>
        todo.id === id
          ? {
              ...todo,
              name: newName,
              description: newDescription,
            }
          : todo
      );
      setTodos(updatedTodos);
    } catch (error) {
      console.log('error updating todo:', error);
    }
  }
  async function removeTodo(id) {
    try {
      await API.graphql(graphqlOperation(deleteTodo, { id }));
      setTodos(todos.filter(todo => todo.id !== id)); // Update the local state to remove the deleted item
    } catch (error) {
      console.log('error deleting todo:', error);
    }
  }
  return (

Run the app to see the new authentication flow protecting the app:

After running now my React JS UI looks like

This is UI coming from the Amplify Default Login and Signup page when we create an account it’s data stored inside the AWS Cognito

Now look in my AWS Cognito insert my New Created account data

After verification of Email now we can able to login

After Successfully Login now I created the new Module for Add the User Data look below where I add, retrieved, Update and delete the data and also Add the Sign-out option are there.

When the User Data put it will show at the DynamoDB

Now I optimize my UI after the Login page
Ø First I created the new modules i.e Header.js


import React from 'react';
import './custom.css';
 
const Header = ({ user, onSignOut }) => {
  return (
<header style={styles.header}>
<div style={styles.logoContainer}>
<img src="/logo192.png" alt="Your Logo" style={styles.logo} />
</div>
<div style={styles.userContainer}>
<p>Welcome, {user.username}</p>
<button onClick={onSignOut} style={styles.signOutButton}>
<img src="/power (1).png" alt="Sign out" style={styles.image} />
</button>
</div>
</header>
);
};
const styles = {
header: {
backgroundColor: 'rgb(26 87 157)',
color: 'white',
display: 'flex',
justifyContent: 'space-between',
padding: '10px 20px',
},
logoContainer: {
flex: 1,
},
image: {
width: '30px', // Set the desired width
height: '30px', // Set the desired height
},

logo: {
width: '100px', // Adjust the logo width as needed
height: 'auto', // Maintain aspect ratio
},
userContainer: {
flex: 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
},
signOutButton: {
backgroundColor: 'transparent',
color: 'white',
border: 'none',
cursor: 'pointer',
},
};

export default Header; 

Ø  Secondly I created the Sidebar.js modules


import React from 'react';
import './custom.css';
import { Link } from 'react-router-dom';
import { Auth } from 'aws-amplify';
const Sidebar = () => {
  const handleSignOut = async () => {
    try {
      await Auth.signOut(); // Sign out the user
    } catch (error) {
      console.error('Error signing out:', error);
    }
  };
return (
<aside className="sidebar">
<ul className="nav flex-column">
<li className="nav-item">
<Link to="/profile">
<a className="nav-link">
<img className="account" src="/MyAccount12.png"/>&nbsp;Profile
</a>
</Link>
</li>
<li className="nav-item">
<a className="nav-link">
<img class="account" src="/setting.png" ></img>&nbsp;Change Password
</a>
</li>
<li className="nav-item">
<a className="nav-link" onClick={handleSignOut}>
<img className="account" src="/MyAccount12.png" />&nbsp;Sign Out
</a>
</li>

</ul>
</aside>
);
};
const styles = {
sidebar: {
backgroundColor: '#333',
color: 'white',
width: '250px',
padding: '20px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},

logo: {
marginBottom: '20px',
},
logoImage: {
width: '100px', // Adjust the logo width as needed
height: 'auto',
},
sidebarList: {
listStyle: 'none',
padding: 0,
textAlign: 'center',
},
sidebarItem: {
marginBottom: '10px',
cursor: 'pointer',
transition: 'background-color 0.2s',
},
};

export default Sidebar;

Ø  Created the custom.css file for design the all the pages


/* custom.css */

/* Custom styles for the sidebar container */
.sidebar {
background-color: #333;
color: white;
width: 250px;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
ul.nav.flex-column {
padding: 0;
}
li.nav-item {
list-style: none;
}
/* Custom styles for the unordered list */
.sidebar ul {
list-style: none;
padding: 0;
}
.row.sidebar_section {
position: relative;
top: 10px;
}
p {
margin-top: 18px;
margin-bottom: 1rem;
}
/* Custom styles for list items */
.sidebar li {
margin-bottom: 10px;
cursor: pointer;
transition: background-color 0.2s;
}
.nav-link:hover {
background-color: #555;
color: #fff;
border-radius: 4px;
}
/* Custom styles for anchor links */
.sidebar a {
text-decoration: none;
color: white;
}

Ø Inside the Index.html I added the CDN link for responsive the React Js website and inside the public add the logo for sidebar and logout.

Now my UI look as follow after login

Now How to Setup AWS Amplify Storage to Upload Files Using S3:

Run the following command from the root of your project:

and select Content in prompted options:

The CLI will walk you though the options to enable Auth, if not enabled previously, and name your S3 bucket. To update your backend run:

Now in my s3 bucket created the new bucket below.

When your backend is successfully updated, your new configuration file aws-exports.js is copied under your source directory, e.g. ‘/src’.

Set Up Routing:

You’ll need to set up routing in your React application to navigate to the profile page when the “Profile” link is clicked.
Here’s a simplified example of how you can set up routing using React Router.

Now we created the ProfilePage.js and ProfileImageUpload.js

/*ProfileImageUpload.js */
import React, { useState,useEffect } from ‘react’;
import { Amplify} from ‘aws-amplify’
import awsExports from “../aws-exports”;
import { Storage } from ‘aws-amplify’;
Amplify.configure(awsExports);

const ProfileImageUpload = () => {
const [selectedFile, setSelectedFile] = useState(null);
const [imageUrl, setImageUrl] = useState(null);
const [imageList, setImageList] = useState([]);
const handleFileChange = (e) => {
const file = e.target.files[0];
setSelectedFile(file);
};

const handleUpload = async () => {
if (selectedFile) {
try {
const result = await Storage.put(`amplify-profile-images/${selectedFile.name}`, selectedFile);
console.log(‘Image uploaded successfully:’, result.key);

// const imageKey = ‘result.key’; // Replace with the actual image key
const imagePath = ‘public’;
const imageUrl = `https://d4mbxhv85310w.cloudfront.net/${imagePath}/${result.key}`;
setImageUrl(imageUrl);

// const s3BucketName = ‘krescitusyakub7197fbda7e6d4432b7500d500d1adb00104049-dev’;
// const imagePath = ‘public’;
// const imageUrl = `https://${s3BucketName}.s3.amazonaws.com/${imagePath}/${result.key}`;

// setImageUrl(imageUrl); // Set the image URL to display
} catch (error) {
console.error(‘Error uploading image:’, error);
}
}
};
useEffect(() => {
// Fetch the list of images from your S3 bucket here
const fetchImages = async () => {
try {

const images = await Storage.list(‘public/amplify-profile-images/’);
console.log(images);
setImageList(images);
} catch (error) {
console.error(‘Error fetching images:’, error);
}
};

fetchImages();
}, []);
return (
<div>
<input type=”file” accept=”image/*” onChange={handleFileChange} />
<button onClick={handleUpload}>Upload Profile Image</button>
{imageUrl && (
<div>
<p>Uploaded Profile Image:</p>
<img src={imageUrl} alt=”Profile Image” style={{ maxWidth: ‘300px’ }} />
</div>
)}
<div>
<h1>Profile Images</h1>
<ul>
{Array.isArray(imageList) ? (
imageList.map((image, index) => (
<li key={index}>
<img

src={`https://d4mbxhv85310w.cloudfront.net/public/${image.key}`}
alt={`Profile Image ${index}`}
style={{ maxWidth: ‘150px’ }}
/>
</li>
))
) : (
<p>No profile images available</p>
)}
</ul>
</div>
</div>

);
};

export default ProfileImageUpload;

Now my App.js finally changed

/* src/App.js */
import { Amplify} from ‘aws-amplify’
import Header from ‘./Header’;
import Sidebar from ‘./Sidebar’;
import { withAuthenticator} from ‘@aws-amplify/ui-react’;
import ‘@aws-amplify/ui-react/styles.css’;
import ProfilePage from ‘./ProfilePage’;
import { BrowserRouter, Route, Routes } from ‘react-router-dom’;
import awsExports from “./aws-exports”;
Amplify.configure(awsExports);

const App = ({ signOut, user }) => {

return (
<BrowserRouter>
<div class=”container-fluid”>
<div className=”row”>
<Header user={user} onSignOut={signOut} />
</div>
<div className=”row sidebar_section”>
<div className=”col-md-3″>
<Sidebar />
</div>
<div className=”col-md-9″>
{/* <Route path=”/profile” component={ProfilePage} />
<Routes>
<Route path=”/profile” element={<ProfilePage />} /> */}
<Routes>
<Route path=”/profile” element={<ProfilePage />} />
</Routes>

</div>
</div>
</div>
</BrowserRouter>

)
}

export default withAuthenticator(App);

When we run the application now my Interface look like below

After Upload the user profile it look like and show the profile image with Cloud Font CDN