Friday, February 24, 2023

Simple crud in ReactJS

Hello
Here I explain simple crud in react js. I hope you finished previous steps of install reactjs in your system. Now do this simple steps. 





How to install react js, follow this url : https://chiragjdsofttech.blogspot.com/2023/02/how-to-install-react-js-in-ubuntu.html




You can also find more details on this url : https://www.w3jar.com/react-js-crud-application/

  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.
  2. Now type on your terminal create-react-app react2.     react2 is our app name or you can also give another name.
  3. Now go inside the react2 folder using cd react2 and then run npm start command on your terminal for checking that your app is running correctly or not.
  4. After that, inside the react2 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.
  5. 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 above image.
  6. Before creating those files, go inside the public folder and open the index.html file on your editor.
  7. In the head section of the index.html, you have to add the Materialize CSS CDN link to create an attractive user interface.
  8. 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;


AddUsers.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.

No comments:

Post a Comment