How to Make Dynamic Cascading Dropdown Box in React JS with PHP

Introduction In this tutorial, we'll explore how to create a dynamic cascading dropdown box using React JS for the front end and PHP f...


Introduction


In this tutorial, we'll explore how to create a dynamic cascading dropdown box using React JS for the front end and PHP for the back end. Cascading dropdowns provide a user-friendly way to filter and select data based on choices made in previous dropdowns.


How to Make Dynamic Cascading Dropdown Box in React JS with PHP


Prerequisites


Before we dive into the tutorial, make sure you have the following installed:

  • Node.js and npm for React development
  • A code editor (e.g., Visual Studio Code, Sublime Text)
  • PHP and a web server (e.g., Apache)

MySQL Database for Cascading Dropdown box


Below you can find country_state_city table sql query. So you have to run this query in your local mysql database which will be used under this Dyanmic Dependent Select box in React.js tutorial.


--
-- Table structure for table `country_state_city`
--
CREATE TABLE `country_state_city` (
  `id` int NOT NULL AUTO_INCREMENT,
  `country` varchar(250) NOT NULL,
  `state` varchar(250) NOT NULL,
  `city` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1;

INSERT INTO `country_state_city` VALUES (1,'USA','New York','New York city'),(2,'USA','New York','Buffalo'),(3,'USA','New York','Albany'),(4,'USA','Alabama','Birmingham'),(5,'USA','Alabama','Montgomery'),(6,'USA','Alabama','Huntsville'),(7,'USA','California','Los Angeles'),(8,'USA','California','San Francisco'),(9,'USA','California','San Diego'),(10,'Canada','Ontario','Toronto'),(11,'Canada','Ontario','Ottawa'),(12,'Canada','British Columbia','Vancouver'),(13,'Canada','British Columbia','Victoria'),(14,'Australia','New South Wales','Sydney'),(15,'Australia','New South Wales','Newcastle'),(16,'Australia','Queensland','City of Brisbane'),(17,'Australia','Queensland','Gold Coast\r\n'),(18,'India','Delhi','New Delhi'),(19,'India','Gujarat','Ahmedabad'),(20,'India','Gujarat','Vadodara'),(21,'India','Maharashtra','Mumbai'),(22,'India','Maharashtra','Pune');





Create React App


Start by creating a new React application, so here in this tutorial, we have already describe step by step to install React JS Application under this React JS CRUD Application tutorial.

Create Dropdown Components


Build components for dynamic cascading dropdown. In this component we will build Country, State and City Select box and then convert into dynamic dependent cascading select box which you can seen below. Here we have make DynamicDropdown.jsx component under this src/Component directory.

src/Component/DynamicDropdown.jsx

import React, { useState, useEffect } from 'react'

function DynamicDropdown(){

	const [countries, setCountries] = useState([]);

	const [states, setStates] = useState([]);

	const [cities, setCities] = useState([]);

	const handleCountryChange = async (event) => {
		const selectedCountry = event.target.value;
		const response = await fetch(`http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php?country=${selectedCountry}`);
		const data = await response.json();
		setStates(data);
		setCities([]);
	};

	const handleStateChange = async (event) => {
		const selectedState = event.target.value;
		const response = await fetch(`http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php?state=${selectedState}`);
		const data = await response.json();
		setCities(data);
	};

	useEffect(() => {

		const fetchCountries = async () => {
			const response = await fetch('http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php');

			const data = await response.json();

			setCountries(data);
		};

		fetchCountries();

	}, []);

	return (

		<div className="container">
            <h1 className="mt-5 mb-5 text-primary text-center"><b>Dynamic Dependent Dropdown Box in React.js</b></h1>

            <div className="card">
                <div className="card-header">Dynamic Dependent Dropdown Box in React.js</div>
                <div className="card-body">
                	<div className="mb-3">
                		<select className="form-select" onChange={handleCountryChange}>
                			<option value="">Select Country</option>
                			{
                				countries.map((country, index) => (
                					<option key={index} value={country.country}>{country.country}</option>
                				))
                			}
                		</select>
                	</div>
                	<div className="mb-3">
                		<select className="form-select" onChange={handleStateChange}>
                			<option value="">Select State</option>
                			{
                				states.map((state, index) => (
                					<option key={index} value={state.state}>{state.state}</option>
                				))
                			}
                		</select>
                	</div>
                	<div className="mb-3">
                		<select className="form-select">
                			<option value="">Select City</option>
                			{
                				cities.map((city, index) => (
                					<option key = {index} value={city.city}>{city.city}</option>
                				))
                			}
                		</select>
                	</div>
                </div>
            </div>
        </div>

	)

}

export default DynamicDropdown;





Below this you can find details description of above provided React JS Component code.


import React, { useState, useEffect } from 'react'


This line imports the necessary modules from the React library. It includes the useState and useEffect hooks, which are essential for managing state and performing side effects in functional components.


function DynamicDropdown() {


This declares a functional component named DynamicDropdown. Functional components are a type of React component that use JavaScript functions to define the behavior of the component.


const [countries, setCountries] = useState([]);
const [states, setStates] = useState([]);
const [cities, setCities] = useState([]);


These lines use the useState hook to create state variables (countries, states, and cities) and their corresponding setter functions. These states will store the data for countries, states, and cities selected by the user.


const handleCountryChange = async (event) => {
		const selectedCountry = event.target.value;
		const response = await fetch(`http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php?country=${selectedCountry}`);
		const data = await response.json();
		setStates(data);
		setCities([]);
	};


This function (handleCountryChange) is an event handler that gets triggered when the value of the country dropdown changes. It fetches data from the server based on the selected country and updates the states state. It also resets the cities state to an empty array.


const handleStateChange = async (event) => {
		const selectedState = event.target.value;
		const response = await fetch(`http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php?state=${selectedState}`);
		const data = await response.json();
		setCities(data);
	};


Similar to handleCountryChange, this function (handleStateChange) is an event handler triggered when the state dropdown value changes. It fetches data from the server based on the selected state and updates the cities state.


useEffect(() => {
		const fetchCountries = async () => {
			const response = await fetch('http://localhost/tutorial/dynamic_dependent_dropdown_box/api/fetch.php');
			const data = await response.json();
			setCountries(data);
		};

		fetchCountries();
	}, []);


The useEffect hook is used here to fetch the list of countries when the component mounts. It calls the fetchCountries function, which makes an asynchronous request to the server and updates the countries state.


return (
		<div className="container">
            <h1 className="mt-5 mb-5 text-primary text-center"><b>Dynamic Dependent Dropdown Box in React.js</b></h1>
            {/* ... */}
		</div>
	)


This is the JSX part of the component. It returns the structure of the component, including HTML elements and React components. The UI contains three dropdowns for selecting country, state, and city, and it includes the necessary event handlers (onChange) for each dropdown.


export default DynamicDropdown;


Finally, this exports the DynamicDropdown component as the default export from this module, making it available for use in other parts of the application.

In summary, this React component creates a dynamic dependent dropdown box where the options in the state and city dropdowns change based on the selected country and state, respectively. The data is fetched from a server using asynchronous requests, and the component uses the useState and useEffect hooks to manage and update its state.

Import Cascading Component in App.jsx

Now we want to import Cascading Component in main React JS Application file which you seen below.

src/App.jsx

import { useState } from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
/*import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'*/
import DynamicDropdown from './Component/DynamicDropdown'

function App() {
  

   return (
      
      <div>
         <DynamicDropdown />
      </div>

  )
}

export default App


Let's break down the provided App.jsx file code line by line:


import { useState } from 'react'


This line imports the useState hook from the React library. In this particular file, it seems unused, so you might consider removing it unless you plan to use state in this component.


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


This line imports the Bootstrap CSS styles. Bootstrap is a popular front-end framework for building responsive and visually appealing web applications. The inclusion of this line suggests that the application may use Bootstrap styles for UI components.


import DynamicDropdown from './Component/DynamicDropdown'


This line imports the DynamicDropdown component from the specified file path. The DynamicDropdown component is likely the one you described in a previous section, responsible for rendering a dynamic dependent dropdown box.


return (
    <div>
      <DynamicDropdown />
    </div>
  )


This is the body of the App component. It returns JSX code, which represents the structure of the component. In this case, it renders a div that contains the DynamicDropdown component.

In summary, this App.jsx file appears to be a simple React application entry point. It imports the necessary dependencies, including the Bootstrap styles and the DynamicDropdown component, and renders the DynamicDropdown component within a div. This structure suggests that the main functionality or UI of the application is encapsulated within the DynamicDropdown component.

Setting Up PHP Backend


Create a new PHP file under api, fetch.php, to fetch data from the server.


<?php

//fetch.php

header("Access-Control-Allow-Origin:* ");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");

$connect = new PDO("mysql:host=127.0.0.1;dbname=testing", "root", "password");

if(isset($_GET['country']))
{
	$query = "SELECT DISTINCT state FROM country_state_city WHERE country = ?";
	$statement = $connect->prepare($query);
	$statement->execute([$_GET['country']]);
	$states = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($states);
}
else if(isset($_GET['state']))
{
	$query = "SELECT DISTINCT city FROM country_state_city WHERE state = ?";
	$statement = $connect->prepare($query);
	$statement->execute([$_GET['state']]);
	$cities = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($cities);
}
else
{
	$query = "SELECT DISTINCT country FROM country_state_city";
	$statement = $connect->query($query);
	$countries = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($countries);
}


?>


This PHP code serves as the backend script for handling requests related to dynamic dependent dropdowns. Let's break it down line by line:


header("Access-Control-Allow-Origin:* ");
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");


These lines set the HTTP headers to enable Cross-Origin Resource Sharing (CORS). CORS headers are essential when your frontend and backend are hosted on different domains to allow requests from the frontend to the backend.


$connect = new PDO("mysql:host=127.0.0.1;dbname=testing", "root", "password");


This line establishes a connection to a MySQL database using the PDO (PHP Data Objects) extension. Adjust the connection parameters (host, dbname, root, password) according to your database configuration.


if(isset($_GET['country']))
{
	$query = "SELECT DISTINCT state FROM country_state_city WHERE country = ?";
	$statement = $connect->prepare($query);
	$statement->execute([$_GET['country']]);
	$states = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($states);
}


This block checks if the request includes a 'country' parameter. If true, it prepares and executes a SQL query to fetch distinct states based on the provided country. The fetched data is then encoded in JSON format and echoed back to the client.


else if(isset($_GET['state']))
{
	$query = "SELECT DISTINCT city FROM country_state_city WHERE state = ?";
	$statement = $connect->prepare($query);
	$statement->execute([$_GET['state']]);
	$cities = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($cities);
}


This block checks if the request includes a 'state' parameter. If true, it prepares and executes a SQL query to fetch distinct cities based on the provided state. The fetched data is then encoded in JSON format and echoed back to the client.


else
{
	$query = "SELECT DISTINCT country FROM country_state_city";
	$statement = $connect->query($query);
	$countries = $statement->fetchAll(PDO::FETCH_ASSOC);
	echo json_encode($countries);
}


If neither 'country' nor 'state' parameters are present in the request, this block executes a SQL query to fetch distinct countries. The fetched data is encoded in JSON format and echoed back to the client.

Run React JS Application


After follow all above step now we need to check output in the browser. So we have goes to terminal and goes into our working directory and run following command.


npm run dev





Once you have run this command then it will start server and provide base url of our React App. So you have to open that url in browser and you can able to view React.js Cascading Dropdown box on web page.

Conclusion


Congratulations! You've successfully created a dynamic cascading dropdown box in React JS with PHP. Feel free to adapt and expand upon this tutorial based on your specific needs.





COMMENTS

Nama

Add,1,Ajax,2,ajax tutorial,1,Ajax with javascript,1,Ajax with node.js,1,application,2,array,1,array to string,1,array to string conversion nodejs,1,array to string in node js,1,array to string nodejs,1,Asynchronous JavaScript,1,authentication,1,authentication node js,1,authorization,1,availability,1,backend,1,bootstrap offcanvas dynamic content,1,bootstrap offcanvas dynamic content node.js,1,bootstrap offcanvas dynamic data,1,bootstrap offcanvas remote dynamic content,1,cart,1,centos 7,1,centos7,1,check,1,contact form node js,1,contact form nodemailer,1,contact us form node,1,conversion,1,create,1,crud,4,crud application,1,crud operation in node js,1,crud operation in node js with mysql,1,CSS,1,data,1,database,1,databases,1,datatables,1,DataTables integration in React.js,1,date range,1,delete,2,download,1,drag &amp; drop,1,drag and drop,1,drag and drop files,1,drag and drop multiple file,1,drag n drop,1,dynamic dropdown in react js,1,dynamic dropdown in react.js,1,ecommerce,2,edit,1,educational project,1,email address,1,email verification,1,email verification using jwt,1,express,3,expressjs,1,fetch,1,file upload,1,file upload in node js,1,files,1,filter,1,Front-end development tutorial,1,Frontend,1,GET,1,how to send email using node js,1,how to send emails in node js,1,html,1,html 2 pdf,1,html to pdf,1,html to pdf node,1,insert,2,insert data in mysql node js,1,Javascript,3,JavaScript tutorial,1,join array nodejs,1,js,1,json,1,jwt,3,jwt authentication,2,jwt authentication node js,1,jwt authentication php,1,jwt email verification,1,jwt login,1,jwt login php,1,jwt php example,1,jwt token,1,jwt token email verification,1,laravel 10,1,laravel 10 tutorial,1,laravel datatables,1,laravel datatables date range filter,1,laravel date filter,1,laravel date range filter,1,last insert id in node,1,learn reactjs,1,linux,1,live,2,live check email address availability,1,live search,1,load more data on click,1,load more data on click javascript,1,load more javscript node.js,1,load more nodejs,1,load more results,1,load more results with node js and ajax,1,login,1,merge 2 arrays in node js,1,merge array in nodejs,1,merge array node,1,merge two array in node js,1,MongoDB,1,mongodb crud,1,mongodb crud operations,1,multer,1,multiple file upload,1,mysql,7,mysql 8,1,mysql tutorial,1,mysql8,1,node,3,node js,8,node js array merge,1,node js array to string,1,node js crud,2,node js crud mysql,1,node js crud operation with mysql,1,node js load more pagination,1,node js mongodb crud,1,node js mysql last insert id,1,node js tutorial,2,node mongodb crud,1,node mysql get last insert id,1,node pdf,1,node.js,8,node.js array,1,node.js crud,1,node.js mysql,1,node.js tutorial,2,nodejs,9,nodejs array,1,nodejs array merge,1,nodejs create pdf,1,nodejs crud,1,nodejs pdf,1,nodejs pdf create,1,nodejs programming,1,offcanvas,1,open source,1,Optimizing web application performance,1,parking management system,1,parking management system in php,1,parking management system project,1,password,1,pdf-creator-node,1,php,3,php jwt authentication example,1,php jwt login,1,php login jwt,1,php parking management system,1,php project,1,PHP server-side processing,1,populate dropdown from database,1,programming tutorial,1,project,1,Puppeteer,1,Puppeteer HTML to PDF,1,React,1,react file upload,1,react js,2,react js dynamic dropdown,1,react js file upload validation,1,react js tutorial,1,react php myql,1,React.js,1,react.js dependent select,1,react.js file upload,1,Reactjs,4,reactJS CRUD,1,reactjs file upload,1,reactjs file upload app,1,reactjs file upload sample code,1,reactjs tutorial,1,read,1,register,1,registration,2,remove,1,request form node,1,reset,1,search,1,select,1,send activation email php,1,sending email using node js,1,server,1,Server-side data processing,1,shopping cart,1,shopping cart in node js,1,shopping cart javascript,1,shopping cart project in javascript,1,shopping cart using node js,1,shopping-cart,1,society management system in php,1,society management system php,1,society management system php source code,1,society management system project in php,1,society management system project php,1,source code,1,string,1,token,2,tutorial,8,update,2,using jwt for email verification,1,vanilla,1,vite,1,vitejs,1,vitejs crud app,1,web development,7,Web development guide,1,webslesson,2,what is jwt authentication,1,
ltr
item
kumpulan driver: How to Make Dynamic Cascading Dropdown Box in React JS with PHP
How to Make Dynamic Cascading Dropdown Box in React JS with PHP
https://i.ytimg.com/vi/KX7ehE0QDJM/hqdefault.jpg
https://i.ytimg.com/vi/KX7ehE0QDJM/default.jpg
kumpulan driver
https://kepsuk.blogspot.com/2023/12/how-to-make-dynamic-cascading-dropdown_25.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2023/12/how-to-make-dynamic-cascading-dropdown_25.html
true
6399859916032798219
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content