Simple React JS CRUD Application

0
28
views
Featured image of React JS CRUD Application

Create Simple React JS CRUD Application

In this tutorial we are creating a simple CRUD application with React JS. To create this we will use React CLI and we don’t use Redux. So let’s create this App –
#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 Prompt and run this command – npm install -g create-react-app. This command will install create-react-app tool Globally on your Machine.

#Step – 1
After that, 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 other 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 folder called components and inside this folder we’ll create some files. To see which files we will create, see the image below.
Structure of the src folder
folder structure
Before creating those files, go inside the public folder and open index.html file on your editor and in the head section, you have to add the Materialize CSS CDN link to create 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 npm start command.

Screenshot of the React JS CRUD Application

Screenshot of the React js crud application

Video Demo of the React JS CRUD Application

LEAVE A REPLY

Please enter your comment!
Please enter your name here