Dependent Drop-down List in ReactJS & PHP

A dependent dropdown list is the best solution if you want to get the user input in one sequence order. The Dependent dropdown is a useful feature when the dropdown data are created with each other. Dependent Drop-down List in ReactJS using PHP

We can make 5 levels dependent dropdown in REACTJS. React (also known as React.js or ReactJS) is an open-source, front-end, JavaScript library for building user interfaces or UI components. We can use ReactJS for any kind of Project

You can down load the code from here : Source Code of the Project

So this is our database design ( Database Name : mulitiple_dropdown )

The below image is our main project which shows how our Project will look a like .

Now first we will create a file Dropdown.js in our React src folder .

import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState, useEffect ,useParams} from "react";
import axios from "axios";


function Dropdown()
{
  const [users, setUser] = useState([]);
  const [req, setReq] = useState({
      stateName:"",
      cityName:""
  });
  const [stadium, setStadium] = useState([]);
  // const { ids } = useParams();

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

  const loadUsers = async () => {
    const result = await axios.get("http://localhost/ajax_all_projects/react_multiple_dropdown/fetch_state.php");
    setUser(result.data.reverse());
  };
 
  // Code for Select city on State click
  const selectState =  (e) => {
    let name = e.target.name;
    let value = e.target.value;
    req[name] = value;
    var data = value;
    alert(data)
  
     var response = fetch("http://localhost/ajax_all_projects/react_multiple_dropdown/fetch_records.php/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: data }),
      }).then(function(response){
        return response.json();
      })
      .then(function(myJson) 
      {
        setReq(myJson)
      })
  };

  const selectCity =  (e) => {
    let name = e.target.name;
    let value = e.target.value;
    req[name] = value;
    var data = value;
    alert(data)
  
     var response = fetch("http://localhost/ajax_all_projects/react_multiple_dropdown/get_stadium_address.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ cityID: data }),
      }).then(function(response){
        return response.json();
      })
      .then(function(myJson) 
      {
        console.log(myJson)
        setStadium(myJson)
      })
  };

  return(
    <div className="container">
    <h3 className="mt-4 text-center text-secondary">Dependent Dropdown in REACT JS</h3>
     <div className="row">
       <div className="col-sm-3">
         <h5 className="mt-5 mb-3">Select State list</h5>
          <select  onChange={selectState} name="stateName" className="form-control mt-3">
            {users.map((user, index) => (
              <option value={user.id}>{user.stateName}</option>
            ))}
          </select>
       </div>

       <div class="col-sm-3">
        <h5 class="text-info mt-5 mb-3">Cities</h5>
         <select onChange={selectCity} name="cityName" class="form-control" >
          {req && req.length>0 && req.map((user, index) => (
              <option value={user.id}>{user.City_Name}</option>
              
            ))}
         </select>
      </div>

      <div class="col-sm-3">
        <h5 class="text-info  mt-5 mb-3">Stadiums List</h5>
        <select  id="stadium" class="form-control">
          {stadium && stadium.length>0 && stadium.map((user, index) => (
              <option value={user.id}>{user.Stadium_list}</option>
            ))}
        </select>
      </div>

      <div class="col-sm-3">
        <h5 class="text-info mt-5 mb-3">Stadiums Address</h5>
        <select id="address" class="form-control">
           {stadium && stadium.length>0 && stadium.map((user, index) => (
              <option value={user.id}>{user.Stadium_Address}</option>
            ))}
       </select>
    </div>

    <div class="col-sm-4 mt-4 offset-sm-4">
        <h5 class="text-info  mb-4">Stadium Details</h5>
           {stadium && stadium.length>0 && stadium.map((user, index) => (
              <option value={user.id}>{user.Stadium_detail}</option>
            ))}
    </div>

  </div>
</div>   

  )
}
export default Dropdown;

Now we will call this file into App.js file

import './App.css';
import Dropdown from './Dropdown';

function App() {
  return (
    <div className="App">
       <Dropdown/>
    </div>
  );
}

export default App;

So our React work is completed now We will make Backend PHP Files . PHP code will fetch data from database

Now create fetch_state.php . This file will fetch state’s record from the database .

<?php

header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

 $conn = mysqli_connect('localhost','root','','mulitiple_dropdown');

/* 
 $stateID = $_POST['stateID']; */

 $sql = "SELECT * FROM states";
 $query = mysqli_query($conn,$sql);

 $output = []; //OR  $output = array(); 
  
    while($row=mysqli_fetch_assoc($query))
    {
        $output[] = array(  
              "id" => $row['id'],  
							"stateName" => $row['state_name'], 
						); 
    }

    echo json_encode($output,JSON_PRETTY_PRINT);
    ?>

Now will write code for city which will depended on the states list . The file name is fetch_record.php

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$conn = mysqli_connect('localhost','root','','mulitiple_dropdown');


$data = json_decode(file_get_contents("php://input"));

$id = $data->id;

$sql = "SELECT city.* from states 
        JOIN city ON states.id = city.state_id 
        WHERE states.id ='".$id."'";

$query = mysqli_query($conn,$sql);

$output = []; //OR  $output = array(); 
 
   while($row=mysqli_fetch_assoc($query))
   {
       $output[] = array(  
             "id" => $row['id'],  
                           "City_Name" => $row['city_name'], 
                       ); 
   }

   echo json_encode($output,JSON_PRETTY_PRINT);
   ?>

Now we will create file for stadium list and details . The file name is get_stadium_address.php

<?php 

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$conn = mysqli_connect("localhost","root","","mulitiple_dropdown");

$data = json_decode(file_get_contents("php://input"));
$ctyID = $data->cityID;

$sql = "SELECT stadium.stadium_name,address.stadium_add,details.stadium_details from city 
        JOIN stadium ON city.id = stadium.city_id 
        JOIN address ON city.id = address.city_id 
        JOIN details ON stadium.id = details.stadium_id 
        WHERE city.id = '".$ctyID."'";

$query = mysqli_query($conn,$sql);

$output =array();

while($row=mysqli_fetch_assoc($query))
 {
    //  $output[] = $row;
    $output[] = array(  
                      "Stadium_list" => $row['stadium_name'], 
                      "Stadium_Address" => $row['stadium_add'], 
                      "Stadium_detail" => $row['stadium_details'], 
                   ); 
 
 }
 echo json_encode($output);

?>

You can down load the code from here : Source Code of the Project

You can get more project here

Leave a Reply

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