Categories

Friday, April 26, 2024
#919814419350 therichposts@gmail.com
Bootstrap 4.5MysqlPhpReactjsReactjs Crud

Reactjs Crud Tutorial – Add User

Reactjs Crud Tutorial - Add User

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Crud Tutorial – Add User.

Reactjs Crud Tutorial Working Example

For reactjs new comers, please check the below link:

Reactjs Basic Tutorials


Friends now I proceed onwards and here is the working code snippet for Reactjs Crud Tutorial – Add User and please use this carefully to avoid the mistakes:

1. Firstly friends we need fresh reactjs setup and for that we need to run below commands into our terminal and also w should have latest node version installed on our system:

npx create-react-app reactadduser

cd reactadduser

npm start // run the project

 

2. Now we need to run below commands to get bootstrap(for good layout), react router and axios(to post data request to php)  modules into our react js app:

npm install --save react-router-dom

npm install bootstrap --save

npm install axios --save

npm start

 

3. Now friends we need to create Home.js file into reactadduser/src folder and after creating file, we need to add below code inside reactadduser/src/Home.js file:

In this component, I am getting data from my php mysql database with axios services get request

import React from 'react';
import './App.css';

//Import link to routing to other components
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';


//bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';


import axios from 'axios';



class Home extends React.Component {
  constructor(props) {
    super(props)
      this.state = {
        data: []
              }
      }

      componentDidMount(){

        axios.get('http://localhost/save.php').then(res => 
        {
        
        this.setState({data: res.data});
           }); 
        
        }
    
 
  render() {
   
    return (
     
      <div className="maincontainer">
        
        <h1 className="mr-5 ml-5 mt-5">Reactjs simple crud tutorial for beginners</h1>
        <div className="container mb-5 mt-5 text-left">
        <button className="bg-primary mb-3"><Link class="nav-link" to={'/adduser'}><span>Add</span><i class="fas fa-user"></i></Link></button>
        <table class="table table-hover table-bordered">
          <thead>
            <tr>
              <th>ID</th>
              <th>Email</th>
              <th>Username</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          {this.state.data.map((result) => {
            return (
             
                 <tr>
                  <td>{result.id}</td>
                  <td>{result.email}</td>
                  <td>{result.username}</td>
                  <td>
                    <button className="bg-info"> <i class="fas fa-eye"></i> </button>
                    <button className="bg-warning"> <i class="fas fa-edit"></i> </button>
                    <button className="bg-danger"> <i class="fas fa-trash"></i> </button>
                  </td>
                </tr>
             
            )
          })}
           
            
          </tbody>
        </table>

        
            
      </div>

    
      </div>
      
)
};
}

export default Home;

 

4. Now friends we need to create AddUser.js file into reactadduser/src folder and after creating file, we need to add below code inside reactadduser/src/AddUser.js file:

In this component, I am adding user to my php mysql datatabse with axios service post request

import React from 'react';
import './App.css';
import { Redirect } from 'react-router';
//bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';

//axios for api request
import axios from 'axios';

class AddUser extends React.Component {
  constructor(props)
    {
      super(props);
      this.addFormData = this.addFormData.bind(this);
    }
  //Form Submission
  addFormData(evt)
    {
      evt.preventDefault();
      const fd = new FormData();
      fd.append('myUsername', this.refs.myUsername.value);
      fd.append('myEmail', this.refs.myEmail.value);
      
      axios.post('http://localhost/save.php', fd
      ).then(res=>
      {
 
    this.myFormRef.reset();

    //Redirect to home page after successfully submission
    this.props.history.push('')
    }
    );
    }
 
  render() {
   
    return (
    
      <div className="maincontainer">
        
        <h1 className="mr-5 ml-5 mt-5">Add User</h1>
        <div className="container mb-5 mt-5 text-left">
        
        <form ref={(el) => this.myFormRef = el}>
        <div className="form-group">
        <input type="email" className="form-control" id="Email" aria-describedby="emailHelp" placeholder="Enter email" ref="myEmail" />
        
        </div>
        <div className="form-group">
        <input type="text" className="form-control" id="Username" placeholder="Enter Username" ref="myUsername" />
        </div>
        <button type="submit" className="btn btn-primary" onClick={this.addFormData}>Submit</button>
      </form>

       
            
      </div>

     
      </div>
      
)
};
}

export default AddUser;

 

5. Now friends we need to create Header.js file into reactadduser/src folder and after creating file, we need to add below code inside reactadduser/src/Header.js file:

I have made this Header.js component as global component, which will show in every component:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
//Import react routes and its other modules
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';
class Header extends React.Component
{
  render()
  {
    return (
      <nav class="navbar navbar-expand-sm bg-primary navbar-dark">
      <ul class="navbar-nav">
        <li class="nav-item active">
        <Link class="nav-link" to={''}>Home</Link>
        </li>
      </ul>
    </nav>
      
    )
  }
}
export default Header;

 

6. Now friends we need to add below code into our reactadduser/src/App.js file to get final output on web browser:

import React from 'react';
import './App.css';

//Import react routes and its other modules
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';

//All components
import AddUser from './AddUser';
import Home from './Home';
import Header from './Header';

//bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';

//Impoert axios services
import axios from 'axios';



class App extends React.Component {
  
 
  render() {
   
    return (
      <Router>
      <div className="maincontainer">
        <Header></Header>
        

        <Switch>
            
            
            <Route exact path='/adduser' component={AddUser} />
            <Route exact path='/home' component={Home} />
            <Route exact path='' component={Home} />
           
          </Switch>
            
      

      
      </div>
      </Router>
)
};
}

export default App;

 

7. Now friends we need to add below CDN links into our reactadduser/public/index.html file to get font awesome icons:ons:

<head>
...
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
</head>

 

8. In the end, we need to add below code inside reactadduser/src/App.css file to add styling :

...
.bg-primary, .bg-warning, .bg-danger, .bg-info{border:none; margin-right: 3px;}
.fa-edit:before,  .fa-user:before, .fa-trash:before, .fa-eye:before{color: #fff;}
.btn{margin-right: 3px;}
button .nav-link {padding: 0px!important;}
button .nav-link span{color: #fff;
    margin: 0 5px 0 5px;
    font-size: 15px;}

 

9. Now friends here is my php code snippet to add,  get data from mysql and show into reactjs and I added this code into my xampp/htdocs/save.php file:

//Please create users database inside phpmysql admin and create userdetails tabel and create id, email and username fields

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "users";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
if(isset($_POST['myEmail']))
{
    $sql = "INSERT INTO userdetails (email, username)
        VALUES ('".$_POST['myEmail']."', '".$_POST['myUsername']."')";
    if (mysqli_query($conn,$sql)) {
    $data = array("data" => "You Data added successfully");
        echo json_encode($data);
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
else
{
    $trp = mysqli_query($conn, "SELECT * from userdetails");
    $rows = array();
    while($r = mysqli_fetch_assoc($trp)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>

 

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Guys in my next post, I will tell you, reactjs php crud operation – view added user in bootstrap modal popup.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.
I will appreciate that if you will tell your views for this post.Nothing matters if your views will good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

4 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.