CURD Create React App, Reactjs Tutorial And React Native

Today we will learn step-by-step examples to find advanced javascript tutorial or CURD Create React App reactjs tutorial that will allow you to do select, insert, delete and update your web app content on desktop applications & mobile React Native app.

Reactjs Tutorial CURD web APP

Hello Friends,

In the previous chapter we will take about static web application and you will get information on install react router dom, install react bootstrap, install react npm, install react router, install react native cli, and other processes of reactjs tutorial. If you have not an idea or not read that article please visit from below so, you will able to understand the CURD application.

Tutorial Link: Reactjs Tutorial And Static Website React Native Web App

Today, we are going to learn how to make an application that has whole user data select, insert, view, delete and update like functions and faster than another website in the website speedtect.

This React js tutorial includes all pages js code and javascript online access that will help you understand how to create react app for CURD operations. Now let’s start with the project.

Now as we discussed in our previous chapter we need to install all required packages but in this CURD application you also need to install some server package that will work for you as database storage or you can use the third-party testing server for development purposes. To run the database server and NPM application you need to install the “Concurrently” package that will allow you to run two servers on different locations with one command.

Install JSON Server

You need to use the below command to install JSON server.

Command: npm i json-server

Now, need to add json run command in package.json file to start the server. But react not allowed us to run two application on same port so, need to use “Concurrently” package.

How To Install Concurrently and Work Process

To install the Concurrently package you need to use the below command.

Command: npm i concurrently

Now you have to make changes to your package (package.json) file. The change looks like the script.

Old json “scripts”:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

After Changes “Scripts” looks like below:

 "scripts": {
    "start": "react-scripts start",
	"json-server":"json-server --watch db.json --port 3003"
	"start:dev": "concurrently \"npm start\" \"npm run json-server\""
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Here db.json is a database file name that will store the whole data and use in the CURD application.

Now to start both applications on 3000 port and another one (json-server) on 3003 port use the below command:

Command: npm run start:dev

This command will start both servers and you can access it on the browser.

Now We will take about each file and talk code so, we can get more understanding about their role in the system.

App.Jsx File Code

import React from 'react';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle';
import Home from './Components/Pages/Home';
import About from './Components/Pages/About';
import Contact from './Components/Pages/Contact';
import Navbar from './Components/Layout/Navbar';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import Notfound from './Components/Pages/Notfound';
import Addusers from './Users/Addusers';
import Editusers from './Users/Edituser';
import User from './Users/User';

function App() {
  return (
    <div className="App">
      <>
      <Router>
      <Navbar />
            <div className="container py-4">
              <Switch>
                <Route exact path="/" component={Home} />
                <Route exact path="/about" component={About} />
                <Route exact path="/contact" component={Contact} />
                <Route exact path="/addusers" component={Addusers} />
                <Route exact path="/editusers/:id" component={Editusers} />
                <Route exact path="/user/:id" component={User} />
                <Route  component={Notfound} />
              </Switch>
            </div>
        </Router>
      </>
    </div>
  );
}

export default App;

Here we have added bootstrap, browserroute, route, switch, component, and user id that we will get in our project to edit, update or delete users by id. The path includes “:id” to bind id in URL. in this case component will run if the browser URL has an id otherwise show a 404 not found page.

About.Jsx File code


import React from 'react';
const About = () => {
    return(
        <>
       THis is about page
       </>
);
}
export default About;

The file is used for access through menu and to show page is redirecting without browser load.

Contact.Jsx File Code

import React from 'react';
const Contact = () => {
    return(
        <>
       THis is contact page
       </>
);
}
export default Contact;

This is same as about.jsx file to show page/component change.

Notfound.Jsx File Code

import React from 'react';
const Notfound=()=>{
    return(
          <>
          <div>Page not found</div>
          </>
    );
}
export default Notfound;

It is used to show a 404-page not found message and will come when a not the related page will found that you are trying to reach.

Home.Jsx File Code

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import { Link, NavLink } from 'react-router-dom';

const Home = () => {

    const [users, setUser] = useState([]);

    useEffect(()=>{

        loadUsers();

    },[]);

    const loadUsers = async () =>{
        const result = await axios.get("http://localhost:3003/users");
        //console.log(result.data);
        setUser(result.data.reverse());
        //setUser(result.data);
    }

    const clickondelete = async id => {
      await axios.delete(`http://localhost:3003/users/${id}`);
      loadUsers();
    }

    return(
            <>
              <table className="table border shadow">
  <thead className="black thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Username</th>
      <th scope="col">Email</th>
      <th scope="col">Phone</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
      {users.map((user, index) => (
            <tr key={index}>
            <td scope="row">{index + 1}</td>
            <td>{user.name}</td>
            <td>{user.username}</td>
            <td>{user.email}</td>
            <td>{user.phnumb}</td>
            <td><NavLink exact to={`/user/${user.id}`} className="btn btn-primary mr-2">View</NavLink>
            <NavLink exact to={`/editusers/${user.id}`} className="btn btn-primary mr-2">Edit</NavLink>
            <Link className="btn btn-primary mr-2 danger" onClick={()=>clickondelete(user.id)} >Delete</Link></td>
          </tr>
          ))}

  </tbody>
</table>

           </>

    );
}

export default Home;

On the home page, we used some functions or react hooks that we will define here in short.

React useState that is used to set current state, manage to add, or update the user states.

React useEffect that is used on page load and here you can define those operations that you want to load instant on page load but it will run in the loop so, you also need to add the rule to let then when it will run or add “[]” to let them just run one time.

Axios, it is a package that is used to connect with servers and send get, post or put request.

Link and NavLink, use for making navigation or link for pages, if you used the link that will reload the browser or use the NavLink then will give the page without loading the browser.

Addusers.JSX File Code

import axios from 'axios';
import React, {useState, useEffect} from 'react';
import {useHistory} from 'react-router-dom';

const Addusers = () =>{

    let history = useHistory();

    const [useradd, setUseradd] = useState({
        name: "",
        username: "",
        email: "",
        website: "",
        phnumb: ""

    });

    //distruction
   const { name, username, email, website, phnumb } = useradd;

   const OnInputChnage = (e) =>{
     //console.log(e.target.value);
     setUseradd({...useradd, [e.target.name]: e.target.value});
   }

   const onSubmitsave = async (e) => {
     e.preventDefault();

     await axios.post("http://localhost:3003/users", useradd);
    history.push("/");

   }

    return (
  
            <>
               <h1>Add User</h1>

               <div className="container">
                   <div className="row">
                       <form onSubmit={e=>onSubmitsave(e) } >
                   <div className="col-8 colorblue">
                        <span>Add your user</span>
                       </div>
                       <div className="col-8">
                           <input type="text" name="name" placeholder="name" value={name} onChange={e=> OnInputChnage(e) }  />
                       </div>
                       <div className="col-8">
                           <input type="text" name="username" placeholder="Username" value={username} onChange={e=> OnInputChnage(e)} />
                       </div>
                       <div className="col-8">
                           <input type="text" name="email" placeholder="Email" value={email} onChange={e=> OnInputChnage(e)} />
                       </div>

                       <div className="col-8">
                           <input type="text" name="website" placeholder="website" value={website} onChange={e=> OnInputChnage(e)} />
                       </div>
                       <div className="col-8">
                           <input type="text" name="phnumb" placeholder="Phonenumber" value={phnumb} onChange={e=> OnInputChnage(e)} />
                       </div>
                        
                       <div className="col-8">
                           <input type="submit" name="submit" />
                       </div>

                       </form>
                   </div>
               </div>
           
            </>
            
    );

}

export default Addusers;

Here we use a new react useHistory hook that is used for redirect on any page after doing any operation. We can not use the redirect method here because the redirect method doesn’t store the previous page.

Here we have to set the initial user state to blank when we are on the add user page. Then we need to store the field value using setstate to store data into memory. To display writing value we need to use “…useradd” this 3 dot value to show the old value when we are targeting to new value otherwise old value will remove.

After on form submit we used axios.post to insert user data.

Await use for wait for the current operation otherwise without completing current things next operation will run. The await comes with async.

Edituser.JSx File Code

import axios from 'axios';
import React, {useState, useEffect} from 'react';
import {useHistory, useParams} from 'react-router-dom';

const Edituser = () =>{

    let history = useHistory();
    let {id} = useParams();

    const [useradd, setUseradd] = useState({
        name: "",
        username: "",
        email: "",
        website: "",
        phnumb: ""

    });

    //distruction
   const { name, username, email, website, phnumb } = useradd;

   const OnInputChnage = (e) =>{
     //console.log(e.target.value);
     setUseradd({...useradd, [e.target.name]: e.target.value});
   }

   const onSubmitsave = async (e) => {
     e.preventDefault();

     await axios.put(`http://localhost:3003/users/${id}`, useradd);
    history.push("/");

   }

   //edit

   useEffect(()=>{
    loadUsers();
   },[]);

   const loadUsers = async (e) =>{
    const result = await axios.get(`http://localhost:3003/users/${id}`);

    setUseradd(result.data);
   // setUser(result.data.reverse());
    //setUser(result.data);
}

    
    return (
  
            <>
               <h1>Edit User</h1>

               <div className="container">
                   <div className="row">
                       <form onSubmit={e=>onSubmitsave(e) } >
                   <div className="col-8 colorblue">
                        <span>Edit your user</span>
                       </div>
                       <div className="col-8">
                           <input type="text" name="name" placeholder="name" value={name} onChange={e=> OnInputChnage(e) }  />
                       </div>
                       <div className="col-8">
                           <input type="text" name="username" placeholder="Username" value={username} onChange={e=> OnInputChnage(e)} />
                       </div>
                       <div className="col-8">
                           <input type="text" name="email" placeholder="Email" value={email} onChange={e=> OnInputChnage(e)} />
                       </div>

                       <div className="col-8">
                           <input type="text" name="website" placeholder="website" value={website} onChange={e=> OnInputChnage(e)} />
                       </div>
                       <div className="col-8">
                           <input type="text" name="phnumb" placeholder="Phonenumber" value={phnumb} onChange={e=> OnInputChnage(e)} />
                       </div>
                        
                       <div className="col-8">
                           <input type="submit" name="submit" />
                       </div>

                       </form>
                   </div>
               </div>
           
            </>
            
    );

}

export default Edituser;

The Edituser.Jsx is the same as Addusers.Jsx but also keep some differences like Addusers request send by post method and Edituser request send by a put request. We need to get the user by its unique id.

User.Jsx File Code

import React, {useState, useEffect} from 'react';
import {useParams} from 'react-router-dom';
import axios from 'axios';

const User=()=>{

    let {id} = useParams();

    const [user, setUser] = useState({
        name: "",
        username: "",
        email: "",
        website: "",
        phnumb: ""

    });

    useEffect(()=>{
        loadUsers(); 
    },[]);

    const loadUsers = async () =>{
        const result = await axios.get(`http://localhost:3003/users/${id}`);
        //console.log(result.data);
        setUser(result.data);
        //setUser(result.data);
    }

    return (
        <>

        <div>Id: {user.id}</div>
        <div>name: {user.name}</div>
        <div>username: {user.username}</div>
        <div>email: {user.email}</div>
        <div>phnumb: {user.phnumb}</div>
        <div>website: {user.website}</div>
        
        </>
    );

}

export default User;

Now the view part of the user system, when we click on view to get any user full data what we do? Here we need to set user info from the data.json file using the id then we can show each user column by oject.namefield like we did here.

data.json file code

{

"users" : [
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  }
]

}

This is a fake JSON database to use to implement the development environments and you can get more from the below URL.

URL Fake Database: https://jsonplaceholder.typicode.com/

Hope React CURD article provides you all information that you want to get for your knowledge to start your own project. You will like our article & share it with your friends or social site to engage us. You can join us on our social media channels to get more latest updates from us.

Stay in touch. Ask Questions.
Lean on us for help, strategies and expertise.

Leave a Reply

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