Creating CRUD application with React JS

React.js CRUD application

28 April

Making use of Crud in React JS: A step by step creation

CRUD operations play a vital role in enabling web applications to interact with data. Using React JS, CRUD operations help users in executing the most fundamental data management tasks, such as generating new records, retrieving existing records, modifying or updating records, and deleting records. These operations enable web applications to function smoothly and efficiently, while providing users with seamless access to data. In essence, CRUD operations accomplished with a built in React JS, act as the cornerstone of web application development and form the basis of most data-driven applications.

Why use Crud in React JS?

CRUD operations are fundamental to any application to manage data. In React, CRUD operations are essential to building dynamic user interfaces and providing a seamless user experience. Here are the reasons why CRUD is important in React:

  • Creating new data: This typically involves collecting user input through a form or dialog box and then submitting that data to the server. With CRUD operations, developers can easily create the necessary UI components and event handlers to manage the data creation process.
  • Reading data: This typically involves retrieving data from the server and displaying it in the UI. With CRUD operations, developers can create components to display the data in various ways, such as tables, lists, or charts.
  • Updating data: This typically involves creating UI components to display the data for editing and then submitting those changes back to the server. With CRUD operations, developers can create the necessary components and event handlers to manage data updates in a structured and consistent way.

Updating data: This typically involves creating UI components to display the data for editing and then submitting those changes back to the server. With CRUD operations, developers can create the necessary components and event handlers to manage data updates in a structured and consistent way.

Building Crud in React through a Step-by-Step Approach

Here is a step-by-step guide to building a CRUD application in React:

  • Set up the project: Start by creating a new React project using a tool like Create React App. This will generate a basic project structure with a few files and folders.
  • Define the data model: Decide on the data model for your CRUD application. This will determine what data to store and how it should be structured. For example, if building a simple to-do list application, a data model might consist of tasks with a name and completion status.
  • Create the component structure: Create a set of React components to represent different parts of a CRUD application. This might include a component to display the list of items, a component to create new items, a component to edit existing items, and a component to delete items.
  • Manage state: Use the useState hook to manage state in components. This allows to keep track of the current list of items, the item being edited or deleted, and any changes made to the item data.
  • Add user interactions: Add event handlers to components to handle user interactions, such as clicking a button to add a new item, clicking a button to edit an existing item, or clicking a button to delete an item.
  • Update the UI: Use React’s virtual DOM and state management to efficiently update the UI when the user interacts with the application. This might involve re-rendering the entire list of items when a new item is added or updating only the specific item being edited when changes are made.

Creating Crud in React with Practical Examples

Let us understand the concept of Crud more closely by looking at a couple of basic examples of creating a CRUD (Create, Read, Update, Delete) application in React JS.

Example 1

Let us assume we want to create a simple application allowing us to manage a list of users.
First, we will create a new React component called Users. This component will render a list of users and allow us perform CRUD operations on them.

 

import React, 
{ useState } from 'react'; 
function Users() { 
    const [users, setUsers] = useState([]); 
    const handleAddUser = (user) => { setUsers([...users, user]); }; 
    const handleDeleteUser = (index) => { setUsers(users.filter((_, i) => i !== index)); }; 
    const handleUpdateUser = (index, user) => { setUsers([ ...users.slice(0, index), user, ...users.slice(index + 1) ]); }; 
    return ( 
        <div> <h1>Users</h1> <UserForm onAddUser={handleAddUser} /> <UserList users={users} onDeleteUser={handleDeleteUser} onUpdateUser={handleUpdateUser} /> </div> ); 
} export default Users;

 

 

In this component, we are using the useState hook to manage the state of our users list. We’re also defining three functions to handle the CRUD operations: handleAddUser, handleDeleteUser, and handleUpdateUser.

Next, we create two new components called UserForm and UserList. The UserForm component will render a form allowing us to add new users, while the UserList component will render a list of existing users and allow us to delete or update them.

 

import React, 
{ useState } from 'react'; 
function UserForm({ onAddUser }) { const [name, setName] = useState(''); 
    const [email, setEmail] = useState(''); 
    const handleSubmit = (event) => { 
        event.preventDefault();
        onAddUser({ name, email });
        setName(''); setEmail(''); 
    };
    
return ( <form onSubmit={handleSubmit}> 
    <input type="text" placeholder="Name" value={name} onChange={(event) => setName(event.target.value)} /> 
    <input type="email" placeholder="Email" value={email} onChange={(event) => setEmail(event.target.value)} /> 
    <button type="submit">Add User</button> 
</form> ); }
 function UserList({ users, onDeleteUser, onUpdateUser }) {
     return ( <ul> {users.map((user, index) => ( 
        <li key={index}> {user.name} ({user.email}) 
            <button onClick={() => onDeleteUser(index)}>Delete</button> 
            <button onClick={() => onUpdateUser(index, user)}>Edit</button> 
        </li>
         ))} </ul> ); 
        } export { UserForm, UserList };

 

 

In the UserForm component, we are using the useState hook to manage the state of our form inputs. When the form is submitted, we call the onAddUser function with the new user object and reset the form inputs. In the UserList component, we’re rendering a list of users and defining two buttons to delete or update each user.

When the delete button is clicked, we call the onDeleteUser function with the index of the user to be deleted. When the edit button is clicked, we call the onUpdateUser function with the index and current user object, and pass it to a new component called UserEditForm, which will render a form with the current user data and allow us to update it.

 

import React, 
{ useState } from 'react'; function UserEditForm({ user, onUpdateUser, onCancel }) {
    const [name, setName] = useState(user.name); const [email, setEmail] = useState(user.email); 
    const handleSubmit = (event) => { 
        event.preventDefault();
        onUpdateUser({ ...user, name, email }); 
    }; 
    return ( <form onSubmit={handleSubmit}> 
        <input type="text" placeholder="Name" value={name} onChange={(event) => setName(event.target.value)} /> 
        <input type="email" placeholder="Email" value={email} onChange={(event) => setEmail(event.target.value)} /> 
        <button type="submit">Update</button> 
        <button type="button" onClick={onCancel}>Cancel</button>
    </form> ); 
} export default UserEditForm;

 

 

Finally, we will update the handleUpdateUser function in the Users component to render the UserEditForm component when the edit button is clicked, and allow us to update the user data.

 

import React, 
{ useState } from 'react'; 
import { UserForm, UserList } from './UserComponents'; 
import UserEditForm from './UserEditForm'; 
function Users() { const [users, setUsers] = useState([]); 
    const [editUser, setEditUser] = useState(null); 
    const handleAddUser = (user) => { setUsers([...users, user]); }; 
    const handleDeleteUser = (index) => { setUsers(users.filter((_, i) => i !== index)); }; 
    const handleUpdateUser = (index, user) => { setEditUser(user); 
    setUsers(users.filter((_, i) => i !== index)); }; 
    const handleCancelUpdate = () => { setEditUser(null); }; 
    const handleSaveUpdate = (user) => { setUsers([...users, user]); setEditUser(null); };
return ( 
        <div> 
            <h1>Users</h1> 
                {editUser ? ( 
                        <UserEditForm user={editUser} onUpdateUser={handleSaveUpdate} onCancel={handleCancelUpdate} />
                    ) : ( <UserForm onAddUser={handleAddUser} /> )
                    } 
                    <UserList users={users} onDeleteUser={handleDeleteUser} onUpdateUser={handleUpdateUser} />      
        </div> 
        ); 
} export default Users;

 

 

In this updated handleUpdateUser function, we are setting the editUser state to the current user object and removing it from the users array. We are also defining two new functions to handle the cancel and save actions of the UserEditForm. When the editUser state is not null, we’re rendering the UserEditForm component instead of the UserForm.

Example 2

Let us create a CRUD application in React JS using functional components and hooks:

 

import React, 
{ useState } from 'react'; function Crud() { 
    const [items, setItems] = useState([ { id: 1, name: 'Item 1', description: 'This is the first item' },
     { id: 2, name: 'Item 2', description: 'This is the second item' }, 
     { id: 3, name: 'Item 3', description: 'This is the third item' }, ]); 
    const [editingItem, setEditingItem] = useState(null); 
    const handleInputChange = (event) => { 
        const { name, value } = event.target;
        setEditingItem((prevEditingItem) => ({ ...prevEditingItem, [name]: value, }));
     }; 
    const handleAddItem = (event) => { 
        event.preventDefault();
        const newItem = { id: Date.now(), name: '', description: '' };
        setItems([...items, newItem]);
        setEditingItem(newItem); 
    };
    const handleEditItem = (item) => { 
        setEditingItem(item); 
    };
    const handleDeleteItem = (item) => { 
        setItems(items.filter((i) => i.id !== item.id));
        setEditingItem(null); 
    }; 
    const handleSaveItem = (event) => { 
        event.preventDefault(); 
        if (!editingItem.name || !editingItem.description) 
        { return; } const newItems = items.map((item) => item.id === editingItem.id ? editingItem : item );
        setItems(newItems);
        setEditingItem(null); 
    }; 
return ( 
    <div> 
        <h1>CRUD Example</h1> 
        <ul> {items.map((item) => ( 
            <li key={item.id}> {editingItem === item ? ( 
                <form onSubmit={handleSaveItem}> 
                    <input type="text" name="name" value={editingItem.name} onChange={handleInputChange} /> 
                    <input type="text" name="description" value={editingItem.description} onChange={handleInputChange} /> 
                    <button type="submit">Save</button> 
                    <button type="button" onClick={() => setEditingItem(null)}> Cancel </button> 
                </form> 
                ) : ( 
                    <div> 
                        <h2>{item.name}</h2> 
                        <p>{item.description}</p> 
                        <button onClick={() => handleEditItem(item)}>Edit</button> 
                        <button onClick={() => handleDeleteItem(item)}>Delete</button> 
                    </div> )
                } 
            </li>
             ))} 
        </ul> 
        <button onClick={handleAddItem}>Add Item</button> 
    </div> ); 
} export default Crud;

 

 

In this example, we are using the useState hook to manage the items and editingItem states. The items state is an array of objects representing the items in the list, and the editingItem state is an object representing the item currently being edited.

We are using the handleInputChange function to update the editingItem state when the user enters data into the input fields. We are also using the handleAddItem, handleEditItem, and handleDeleteItem functions to add, edit, and delete items in the list. Finally, we are using the handleSaveItem function to save changes made to an item in the list.

Summing Up

Overall, CRUD is essential to build dynamic and interactive applications in React. Developers can create a consistent and predictable user experience, while ensuring data is managed safely and securely.

React JS With Docker

ReactJS App With Docker

28 April

Creating a ReactJS application with Docker – All you need to know

ReactJS is a popular JavaScript library used for building dynamic and interactive user interfaces. Docker is a popular platform that simplifies the deployment and management of applications. Combining ReactJS with Docker allows developers to easily create, manage, and deploy their React applications.

Here is a step-by-step guide on how to set up ReactJS with Docker:

Step 1: Create a new ReactJS project Create a new ReactJS project using the create-react-app CLI tool. Open a terminal and run the following command:

npx create-react-app my-app

Step 2: Create a Dockerfile In order to build a Docker image for the ReactJS application, we need to create a Dockerfile. The Dockerfile describes the image that we want to build. Create a new file called Dockerfile in the root directory of your ReactJS project and add the following contents:

FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [“npm”, “start”]

This Dockerfile specifies that the image should be based on the official Node.js 14 Alpine image. It also sets the working directory to /app, copies the package.json and package-lock.json files, installs the dependencies, copies the rest of the application code, exposes port 3000, and starts the application using the npm start command.

Step 3: Build the Docker image To build the Docker image, navigate to the root directory of your ReactJS project in a terminal and run the following command:

docker build -t my-react-app.

This command builds a Docker image with the name my-react-app, using the Dockerfile in the current directory.

Step 4: Run the Docker container Once the Docker image is built, we can run the Docker container using the following command:

docker run -p 3000:3000 my-react-app

This command runs the Docker container with the name my-react-app and maps port 3000 on the host machine to port 3000 in the Docker container.

Step 5: Access the ReactJS application Finally, open a web browser and navigate to http://localhost:3000 to access the ReactJS application running inside the Docker container.

Setting up ReactJS with Docker involves creating a Dockerfile, building a Docker image, and running a Docker container. Docker do simplify the deployment and management of ReactJS applications with a consistent and isolated environment.

Using Docker to Setup a ReactJS Application

We will look at a couple of ways to set up a React JS application with Docker can be a great way to ensure that your development environment is consistent across multiple machines and easily portable.

Method 1

This method uses the default port of create-react-app, which is 3000, and exposes it to the host machine using the EXPOSE command in the Dockerfile. The app is run with the “npm start” command, which starts the development server. The Dockerfile simply copies the app files to the container, installs any necessary dependencies, and runs the app.

  • Create a new React JS app using create-react-app by running the following command in your terminal:
    npx create-react-app my-app
  • Change your current working directory to the newly created app directory by running the following command:
    cd my-app
  • Create a new Dockerfile in the root directory of your app by running the following command:
    ouch Dockerfilet
  • Open the Dockerfile in your preferred text editor and add the following code:
    # Use an official Node.js runtime as a parent image
    FROM node:14-alpine
    # Set the working directory to /app
    WORKDIR /app
    # Copy the current directory contents into the container at /app
    COPY . /app
    # Install any needed packages
    RUN npm install
    # Make port 3000 available to the world outside this container
    EXPOSE 3000
    # Run app.js when the container launches
    CMD [“npm”, “start”]

This Dockerfile uses the official Node.js Docker image, sets the working directory to /app, copies the current directory (i.e., your React app) into the container, installs any needed packages with npm install, exposes port 3000 (the default port used by create-react-app), and runs the app with npm start.

  • Build a Docker image by running the following command:
    docker build -t my-app.

     

This command will build a Docker image with the name my-app using the Dockerfile in the current directory.

  • Once the image is built, you can run a container with the following command:
    docker run -it –rm -p 3000:3000 my-app

This command will start a container based on the my-app image, open port 3000 on the host machine (i.e., your computer) and map it to port 3000 inside the container, and remove the container automatically when you stop it (–rm option).

  • Now you should be able to view your React app by opening a web browser and navigating to http://localhost:3000.

This is a simpler method intended for development purposes.

Method 2

This method builds the React app using the “npm run build” command and serves it using the “serve” package. The app is served on port 80 and this port is exposed to the host machine using the EXPOSE command in the Dockerfile. This method copies both the package.json and package-lock.json files to the container and installs the dependencies using the “npm install” command. Then it copies the rest of the app files to the container and builds the app before running it using the “serve” command.

  • Create a new React JS app using create-react-app by running the following command in your terminal:
    npx create-react-app my-app
  • Change your current working directory to the newly created app directory by running the following command:
    cd my-app
  • Create a new Dockerfile in the root directory of your app by running the following command:
    touch Dockerfile
  • Open the Dockerfile in your preferred text editor and add the following code:
    # Use an official Node.js runtime as a parent image
    FROM node:14-alpine
    # Set the working directory to /app
    WORKDIR /app
    # Copy the package.json and package-lock.json files to the container
    COPY package*.json ./
    # Install any needed packages
    RUN npm install
    # Copy the rest of the application files to the container
    COPY . .
    # Build the application
    RUN npm run build
    # Make port 80 available to the world outside this container
    EXPOSE 80
    # Run the application with serve
    CMD [“npx”, “serve”, “-s”, “build”, “-l”, “80”]

This Dockerfile uses the official Node.js Docker image, sets the working directory to /app, copies the package.json and package-lock.json files to the container, installs any needed packages with npm install, copies the rest of the application files to the container, builds the application with npm run build, exposes port 80, and runs the application with the serve package.

    • Build a Docker image by running the following command:
docker build -t my-app.

This command will build a Docker image with the name my-app using the Dockerfile in the current directory.

    • Once the image is built, you can run a container with the following command:
docker run -it –rm -p 80:80 my-app

This command will start a container based on the my-app image, open port 80 on the host machine (i.e., your computer) and map it to port 80 inside the container, and remove the container automatically when you stop it (–rm option).

  • Now you should be able to view your React app by opening a web browser and navigating to http://localhost.
  • This method is more suitable for production environments because it builds and serves a more optimized version of the app.

Last Few Words to Sum Up

We looked at a couple of ways to set up a ReactJS application with Docker. However, with more knowledge on this, one can set up ReactJS with Docker in a few other ways as well. Not to mention, it does offer several benefits for developers. Here are some of the reasons why developers may choose to use Docker for their ReactJS projects:

  • Consistency: Docker provides a consistent environment for developing and deploying ReactJS applications. Developers can be sure that their application will work the same way across different environments, making it easier to deploy and manage their application.
  • Isolation: Docker allows for isolation between the application and the host machine. This means that the application is less likely to be affected by changes to the host system, making it more stable and reliable.
  • Scalability: Docker makes it easy to scale up or down the application based on demand. Developers can quickly spin up new containers to handle increased traffic or scale down when traffic decreases, without having to worry about the underlying infrastructure.
  • Portability: Docker containers can be easily moved between different environments, making it easier to deploy the application to different hosting providers or cloud platforms.
  • Packaging: Docker allows developers to package the application and its dependencies into a single image, making it easier to share and deploy the application across different environments.

Using Docker for ReactJS projects provides a consistent, isolated, scalable, portable, and efficient environment for developing and deploying applications.
Method 1 is simpler and is intended for development purposes, while Method 2 is more suitable for production environments because it builds and serves a more optimized version of the app.

React JS installation and Setup

24 March

Introduction of React

React JS is the top UI framework in the world . It is trendy and cool and revolves around a lot of debate loops in front end web development compared to Angular or Vue JS and what not . There are a lot of missing introductions to React JS that people do not know.

We generally find HTML, CSS, Javascript as the prerequisites to start on with the React framework, or is it a framework that is also debatable. But we never try to find the importance and need of React JS before setting up the project or running the npx create-react-app command.

We should officially first know a bit about what React is all about in its first place so that many learners like us do not mug up the most popular and life-saving UI framework.

Foremost, React is a library to create User Interfaces in web applications where a library is a mechanism with less code and less rules in which you can just easily inject your code without any worry of routing or other parameters unlikely frameworks follow a full-fledged mechanism to work with.

React is nothing but a piece of JavaScript code that we are injecting in our code, making it the hottest library in the whole JavaScript ecosystem. With React , web developers develop and code web applications that avoid racing conditions and mutable states of DOM following the VDOM concept that can refresh the web page and re-render the UI automatically.

Why is React Needed?

React is a component based library that uses VDOM concept so that Model and User Interface in MVC architecture can directly communicate to each other without any interference of Controller such that any new change in the website could refresh or reload that component only in which changes are done instead of loading back the whole page that just upgrades and scales up the speed efficiency of websites and made the user experience even better.

Installation of React Application

The installation of React includes some prerequisite JavaScript environments , Node package Manager and NodeJS.

Step 1 : Browse your google chrome or any search engine to search for NodeJS , you will find the top most official link of NodeJS to get it download and installed in compatibility to your window or mac workstation configuration from https://nodejs.org/en/download/

Download For MacOS

Step 2 : Select an appropriate code editor to perform code implementation , the best says it is visual studio code to be installed in compatible to the system configuration of windows or mac from https://code.visualstudio.com/download

Download Visule Studio Code Step 3 : Configure the downloaded executable files of NodeJS and Visual Studio Code in your system successfully.

Step 4 : Browse the command line terminal in your machine using cmd and type the following command to check if the Node JS is executed successfully : node -v which tells about which node version is installed successfully.

Set Up React Application

After the prerequisites are successfully installed in the system from the steps mentioned above, we can set up the React and inject React Library in the already installed Javascript environment.

Step 1 : Create a folder on your desktop with name for say my-react-app

React App File

Step 2 : Go to the visual studio code editor that you have just installed following the steps mentioned above and open that particular folder in the code editor.

Step 3 : The visual code editor gives an inline command terminal to execute commands for installation and configuration of later on packages and libraries that are managed by NodePackage Manager ( NPM ) which came automatically. bundled with installation of NodeJS itself.

Step 4 : One of the easiest ways of setting up a new react app is to type i the following command in the terminal saying

Command :  npx create-react-app <app name>

npx create-react-app my-react-app

The command npx create react app will create a quick and running React project in the frontend pipeline customized to your project and the project name. It does not take any configuration manually, instead it installs all web pack dependencies, backend configurations and other tools and packages in one whole create react app for you to ignite React easily in your code.

React Code1

Step 5 : Once the above code injects React easily in your project and your code, the following modules and packages are installed.

  • Node_modules contains all the dependencies of the project that can be the packages to be installed using NPM ( node package manager )
  • The public/ folder contains public assets like index.html that renders the main UI to the user on the screen.
  • src/ folder is where you find the core of JavaScript and react implementation in the code as well , where you find inside App.js which is the main react file that is rendered on the screen using index.html as the base template and css file for styling the webpage. It is the starting point of React Application in whole.

React Code2

Run the React Application

Once the React project is created and we overview every file present in it, the particular react project can be run using the following steps mentioned above :

Step 1 : The command npm start will run the development web server and the basic React project will be loaded on the local server.

Step 2 : The browser is automatically opened and the URL is created at the local host of the default 3000 port to see the following React created website on the screen. It is a default generation by the React library which is injected in our code.
React Code Terminal
React Learn

Conclusion

This ends us up to the biggest kickstarter of React application from its introduction and its place in web development to the installation and setting it up according to your workstation and system is quite easy and on the flow to proceed to the world of React magically.