React  — Input Data Binding


Drop-Downs

Dropdowns is a common form input control element added to many apps. It’s the select element in HTML. In React, we have to set the value attribute of the select element to the value we selected in addition to adding the onChange handler to add a handler to get the selected value and set it as the state.

For instance, we write the following code to do that:

 
   

    import React, { useState } from "react";

    function Form() {
    const [foodState, setFoodState] = useState("dumpling");

    return (
        <div className="container p-5">
        <select
            className="custom-select"
            value={foodState}
            onChange={(e) => {
            const selectedFood = e.target.value;
            setFoodState(selectedFood);
            }}
        >
            <option value="steak">Steak</option>
            <option value="sandwich">Sandwich</option>
            <option value="dumpling">Dumpling</option>
        </select>
        {foodState}
        </div>
    );
    }

    export default Form;

Cascading dropdowns in React JS

Step 1 : Take a list of states and cities object related to every state or we can get this data using apis.

Step 2 : Loop over the states data to show dropdown related to All States.

Step 3 : Now save the selected state.

Step 4 : Based on selected state value , get the corresponding cities and show them in dropdown as follows :


    
        import { useState } from "react";

        function Form() {
        const states = ['UP', 'Delhi', 'Gujrat']
        const cities = {
            'UP': ['f', 'g', 'l'],
            'Delhi': ['a', 'b'],
            'Gujrat': ['tr', 'trt', 'rtt'],
        }

        const [selectedState, setSelectedState] = useState('')  
        console.log(selectedState)

        return (
            <div>
            CASCADING DROPDOWNS :
            <select onChange={(e) => { setSelectedState(e.target.value) }}>
                {
                states.map(state => {
                    return <option>{state}</option>
                })
                }
            </select>

            {selectedState && <select>
                {
                cities[selectedState].map(city => {
                    return <option>{city}</option>
                })
                }
            </select>}

            </div>
        );
        }

        export default Form;