search
HomeWeb Front-endJS TutorialCascading form React Native Improved

I want to share my 3 approaches of handling cascading form fields.

  1. First one is general common approach, using state variables.
  2. Second is to use ordinary variables and one boolean state variable to trigger the state effect (refresh page).
  3. Third is, dynamic form fields with ordinary variables.

First Approach, using state variables

Here in this post we see the second approach, using ordinary variables to handle cascading form fields based on country, state, city data.

Packages

react-native-element-dropdown
react-native-paper

we are using react-native-element-dropdown for drop down fields

Base Page

Cascading form React Native Improved

import React, { useState, useEffect } from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { Dropdown } from "react-native-element-dropdown";

export default function App() {
  return (
    <view>



<p>ZDropDown is a custom component. </p>

<h3>
  
  
  Sample data
</h3>



<pre class="brush:php;toolbar:false">const listCountry = [
  { countryId: "1", name: "india" },
  { countryId: "2", name: "uk" },
  { countryId: "3", name: "canada" },
  { countryId: "4", name: "us" },
];

const listSate = [
  { stateId: "1", countryId: "1", name: "state1_india" },
  { stateId: "4", countryId: "2", name: "state1_uk" },
  { stateId: "7", countryId: "3", name: "state1_canada" },
  { stateId: "10", countryId: "4", name: "state1_us" },
];

const listCity = [
  {
    cityId: "1",
    stateId: "1",
    countryId: "1",
    name: "city1_state1_country1",
  },
   {
    cityId: "6",
    stateId: "2",
    countryId: "1",
    name: "city6_state2_country1",
  },
  {
    cityId: "7",
    stateId: "3",
    countryId: "1",
    name: "city7_state3_country1",
  }, 
  {
    cityId: "23",
    stateId: "8",
    countryId: "3",
    name: "city23_state8_country3",
  }, 
  {
    cityId: "30",
    stateId: "10",
    countryId: "4",
    name: "city30_state10_country4",
  }, 
  {
    cityId: "35",
    stateId: "12",
    countryId: "4",
    name: "city35_state12_country4",
  },
  {
    cityId: "36",
    stateId: "12",
    countryId: "4",
    name: "city36_state12_country4",
  },
];

Form Variables

In the first approach we used 4 state variables but here we use 4 ordinary variables (3 for dropdown, 1 for focus field) and a state variable which is used to switch and trigger the state effect (refresh page).

var country = {
  list: [],
  selectedCountry: {},
  selectedValue: null,
};

var state = {
  list: [],
  selectedState: {},
  selectedValue: null,
};

var city = {
  list: [],
  selectedCity: {},
  selectedValue: null,
};

var focusField = '';

export default function App() {
 const [refreshPage, setRefreshPage] = useState(false);

  return (
    <view>



<p>Focus and Blur events get triggered more than onChange event so it is better to maintain a separate variable to represent the focus field and avoid data mess up situations. </p>

<h3>
  
  
  Load Country
</h3>

<p>Load country dropdown from the sample data. (you can use api call)<br>
</p>

<pre class="brush:php;toolbar:false">export default function App() {
. . .
  const loadCountry = () => {
    // load data from api call
    country.list = [...listCountry];
    // switching value will refresh the ui
    setRefreshPage(!refreshPage);
  };

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

return (
. . .
)

Focus / Blur

We're using a function to set the focus field and refresh the page by switching the state variable(refreshPage)

  const changeFocusField = (fld = '') => {
    focusField = fld;
    setRefreshPage(!refreshPage);
  };
        <text>Country</text>
        <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('country')}
          onBlur={() => changeFocusField('')}
          onChange={null}
        />
        <text>State</text>
        <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('state')}
          onBlur={() => changeFocusField('')}
          onChange={null}
        />
        <text>City</text>
        <zdropdown . isfocus="{focusField" onfocus="{()"> changeFocusField('city')}
          onBlur={() => changeFocusField('')}
          onChange={null}       
        />
</zdropdown></zdropdown></zdropdown>

Cascading form React Native Improved

We are half way done now.

Load State STATE

On country selected, we need to load the respective states STATES based on the country selection.

Update country field, focus off country and load STATES based on country.

  <text>Country</text>
  <zdropdown . onchange="{(item)"> {
      country.selectedCountry = item;
      country.selectedValue = item.countryId;
      focusField = '';
      loadState();
    }}
  />
</zdropdown>

Did you see the difference in the first approach? Previously there were 3 state variables updated but here only one state variable gets updated.

When country changed, both states and cities will be changed. So before setting up the new value we need to clear the existing data.

 const loadState = async () => {
   state = { list: [], selectedState: {}, selectedValue: null };
   city = { list: [], selectedCity: {}, selectedValue: null };
   const arr = listSate.filter(
     (ele) => ele.countryId === country.selectedValue
   );
   if (arr.length) {
     state.list = arr;
   }
   refreshPage(!refreshPage);
 };

Cascading form React Native Improved

Load City

And load city field based on country and state.

    <text>State</text>
    <zdropdown . onchange="{(item)"> {
        state.selectedValue = item.stateId;
        state.selectedState = item;
        changeFocusField('');
        loadCity();
      }}
     />
</zdropdown>
  const loadCity = async () => {
    city = { list: [], selectedCity: {}, selectedValue: null };
    const arr = listCity.filter((ele) => ele.stateId === state.selectedValue);
    if (arr.length) city.list = arr;
    setRefreshPage(!refreshPage);
  };

Cascading form React Native Improved

All set, the form fields are working properly now.

Cascading form React Native Improved

2 more additional features, one is resetting the page and the other one is show warning.

Reset page

Form variables and focus variable should be cleared.

. . .
  const resetForm = () => {
    country = {list: [...listCountry],selectedCountry: {}, selectedValue: null};
    state = { list: [], selectedState: {}, selectedValue: null };
    city = { list: [], selectedCity: {}, selectedValue: null };
    focusField = '';
    setRefreshPage(!refreshPage);
  };
. . .

  <touchableopacity onpress="{()"> resetForm()}>



<h3>
  
  
  Warning
</h3>

<p>We have to show a warning msg if the parent field value is null. For that we are using SnackBar component from paper.<br>
</p>

<pre class="brush:php;toolbar:false">import { Snackbar } from "react-native-paper";
. . .
var snackMsg = '';
export default function App() {
  . . .
  const [visible, setVisible] = useState(false);

  const onToggleSnackBar = () => setVisible(!visible);
  const onDismissSnackBar = () => setVisible(false);
  . . .

  return (
    <view>



<p>We moved snackMsg to ordinary variable from state variable.</p>

<p>Since State and City fields have parent field, they have to be validated.<br>
</p>

<pre class="brush:php;toolbar:false">        <text>State</text>
        <zdropdown onfocus="{()"> {
            focusField('state');
            if (!country.selectedValue) {
              snackMsg = 'Select country';
              onToggleSnackBar();
              changeFocusField('country');
            }
          }}
          . . .
        />
        <text>City</text>
        <zdropdown onfocus="{()"> {
            focusField('city');
            if (!country.selectedValue) {
              snackMsg = 'Select country';
              onToggleSnackBar();
              changeFocusField('country');
            } else if (!state.selectedValue) {
              snackMsg = 'Select state';
              onToggleSnackBar();
              changeFocusField('state');
            }
          }}
          . . .
        />
</zdropdown></zdropdown>

Cascading form React Native Improved

Done.

Thank you.

Full code reference here

The above is the detailed content of Cascading form React Native Improved. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.