Cascading form React Native Improved
I want to share my 3 approaches of handling cascading form fields.
- First one is general common approach, using state variables.
- Second is to use ordinary variables and one boolean state variable to trigger the state effect (refresh page).
- 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
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 === 'country'} onFocus={() => changeFocusField('country')} onBlur={() => changeFocusField('')} onChange={null} /> <Text>State</Text> <ZDropDown . . . isFocus={focusField === 'state'} onFocus={() => changeFocusField('state')} onBlur={() => changeFocusField('')} onChange={null} /> <Text>City</Text> <ZDropDown . . . isFocus={focusField === 'city'} onFocus={() => changeFocusField('city')} onBlur={() => changeFocusField('')} onChange={null} />
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(); }} />
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); };
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(); }} />
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); };
All set, the form fields are working properly now.
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'); } }} . . . />
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.
