React JS CRUD Application

Create a Simple React JS CRUD Application

In this tutorial we are creating a simple React JS CRUD application.

To create this we will use React CLI, but we don’t use Redux.

Before we start to create this CRUD app if you want to see a demo of this application then watch the below video.

DEMO

Screenshot of the React JS CRUD Application
Screenshot

Getting started

Before starting you need to install Node JS on you Machine / Computer.

After installing Node js then you need to install one more thing it’s create-react-app.

create-react-app is a tool it’s built by Facebook to help you build React Application.


How to install Create React App?

After installing Node JS, open your Terminal / Command Promptand run this command – npm install -g create-react-app.

This command will install create-react-app tool Globally on your Machine.


After installing the create-react-app then follow the below steps.

Step – 1

Open your Terminal or command prompt and go to the folder or desktop, using cd path where you want to create your Very first React Application.

Now type on your terminal create-react-app crud. crud is our app name or you can also give another name.


Step – 2

Now go inside the crud folder using cd crud and then run npm start command on your terminal for checking that your app is running correctly or not.

After that, inside the crud folder, we are seeing some files and folders, here you can see the src folder, go inside this folder and delete some files such as App.js, App.test.js, App.css, and logo.svg.


Step – 3

After that, inside the src folder, we’ll create a new folder called components and inside this components folder, we’ll create some files. To see which files we will create, see the image below.

structure of the React applications source folder

Before creating those files, go inside the public folder and open the index.html file on your editor.

In the head section of the index.html, you have to add the Materialize CSS CDN link to create an attractive user interface.


Now we will create our files

Inside the components folder, we will create three files – App.js, Users.js, and AddUser.js.

App.js

import React, { Component } from 'react';
import Users from './Users';
import AddUser from './AddUser';

class App extends Component{

    // Default dummy data
    state = {

        users:[
          {name:"Travis Jackson", age:18, isEditing:false},
          {name:"Linda Moorhouse", age:22, isEditing:false},
          {name:"Jeffrey Delgado", age:21, isEditing:false}
    
        ]
      }
      // (newUser) is received from AddUser.js
      addUser = (newUser) => {
            let users = [...this.state.users, newUser];
            this.setState({
                users
            });     
      }

      // when press edit button
      // (i) is received from Users.js
      pressEditBtn = (i) => {
        let users = this.state.users;
        users[i].isEditing = true;
        this.setState({
            users
        });
      }

      // (i, name, age) is received from Users.js
      updateUser = (i, name, age) => {
        let users = this.state.users;
        users[i].name = name;
        users[i].age = age;
        users[i].isEditing = false;

        this.setState({
            users
        });

      }
      // (i) is received from Users.js
      pressDelete = (i) => {
        let users = this.state.users.filter((u,index)=>{
            return index !== i;
        });
        this.setState({
            users
        });
      }

    render(){
        return(
            <div className="container">
                <h1>CRUD with React CLI</h1>
                <Users allUsers={this.state.users} pressEditBtn={this.pressEditBtn} updateUser={this.updateUser} pressDelete={this.pressDelete} />
                <AddUser addUser={this.addUser}/>
            </div>
        );
    }
}

export default App;

Users.js

import React, { Component } from 'react';

class Users extends Component{

    // call updateUser (App.js)
    handleUpdate = () => {
        this.props.updateUser(this.indexNum, this.name.value, this.age.value);
    }

    render(){

        const {allUsers, pressEditBtn, pressDelete} = this.props;

        const usersList = allUsers.map((user, index) => {

            return user.isEditing === true ? (
                
                <tr  key={index}>
                    <td><input type="text" ref={(val) => {this.name = val}} required defaultValue={user.name}/></td>
                    <td><input type="number" ref={(val) => {this.age = val}} required defaultValue={user.age}/></td>
                    <td>
                    <input type="button" value="Update" onClick={this.handleUpdate} ref={() => {this.indexNum = index}} className="btn green"/>
                    </td>
                </tr>  

            ) : (

                <tr  key={index}>
                    <td>{user.name}</td>
                    <td>{user.age}</td>
                    <td><button className="btn white black-text" onClick={() => pressEditBtn(index)}>Edit</button>  |  <button className="btn red" onClick={()=>pressDelete(index)}>Delete</button></td>
                </tr>

            );
        });

        return(
            <table className="striped">
                <thead>
                    <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {usersList}
                </tbody>
            </table>
        );
    }
}

export default Users;

AddUser.js

import React,{ Component } from 'react';

class AddUser extends Component{

    state = {
        name:null,
        age:null,
        isEditing:false
    }
    //call addUser (App.js)
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addUser(this.state);  
        e.target.reset();

    }
    // update state
    updateState = (e) => {
        this.setState({
            [e.target.name]:e.target.value,
        });
    }

    render(){
        return(
            <div className="row">
                <form onSubmit={this.handleSubmit}>
                    <div className="input-field col s4">
                        <input name="name" autoComplete="off" placeholder="Enter your name" required type="text" onChange={ this.updateState} />
                    </div>
                    <div className="input-field col s2">
                        <input name="age" autoComplete="off" type="number" required placeholder="Enter your age" onChange={ this.updateState } />
                    </div>
                    <div className="input-field col s2">
                        <input type="submit" value="Add +" className="btn blue"/>
                    </div>
                </form>
            </div>
        );
    }
}
export default AddUser;

After complete that now edit your index.js file –

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import './index.css';

ReactDOM.render(<App />,document.getElementById('root'));

Now select your app directory on your terminal and run your app by typing the npm start command.


Learn also:

How to create React JS Navigation bar using React Router DOM

Posts Navigation


2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *