DEV Community

Deva I
Deva I

Posted on

useState Scenario questions - 2

5. You have 5 input fields (name, email, phone, city, password).

1.Better to use:
5.separate useState? OR one object state? Why?

✓ One object state is generally better for 5 input fields .

✓ Why: It keeps the code cleaner, allows for a single handleChange function using the name attribute of inputs, and makes the data easier to send to an API.

2.What problem happens if you update object state incorrectly?

✓ If you update an object state without spreading(...spread) the previous state, you will overwrite and lose all other fields (email, phone, etc.).

CODE :

import { useState } from "react";

function MultiInput() {
    const [form, setForm] = useState({
        name: "",
        email: "",
        phone: "",
        city: "",
        password: "",
    })
    const handleChange = (d) => {
        setForm({ ...form, [d.target.name]: d.target.value });
    }

    return (
        <div>
            <input type="text"
                name="name"
                placeholder="Name"
                value={form.name}
                onChange={handleChange} />

            <br />

            <input type="email"
                name="email"
                placeholder="Email"
                value={form.email}
                onChange={handleChange} />

            <br />

            <input type="text"
                name="phone"
                placeholder="Phone"
                value={form.phone}
                onChange={handleChange} />

            <br />

            <input type="text"
                name="city"
                placeholder="City"
                value={form.city}
                onChange={handleChange} />

            <br />

            <input
                type="password"
                name="password"
                placeholder="Password"
                value={form.password}
                onChange={handleChange} />

            <h2>Form Data</h2>

            <p>Name: {form.name}</p>
            <p>Email: {form.email}</p>
            <p>Phone: {form.phone}</p>
            <p>City: {form.city}</p>
            <p>Password: {form.password}</p>


        </div>
    )
}
export default MultiInput;
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

6. Checkbox Selection List

User can select multiple skills:
React,Node,Java,SQL

1.What should be the state type?

✓ An array of strings

2.How will you add/remove values from state array?

✓ Add: Use the spread operator.

✓ Remove: Use the .filter() method.

CODE :

import { useState } from "react";

function Checkboxhandling() {
    const [courses, setCourses] = useState([])

    function getUserInput(e) {
        const { value, checked } = e.target;

        if (checked) {
            setCourses([...courses, value])
        }
        else {
            setCourses(courses.filter((course) => course != value))
        }
    }

    return (
        <div>
            <label htmlFor="react">React</label>
            <input id="react" value="React" type="checkbox" onChange={getUserInput} />
            <br />

            <label htmlFor="node">Node</label>
            <input id="node" value="Node" type="checkbox" onChange={getUserInput} />
            <br />

            <label htmlFor="js">Javascript</label>
            <input id="js" value="javascript" type="checkbox" onChange={getUserInput} />
            <br />

            <label htmlFor="java">Java</label>
            <input id="java" value="Java" type="checkbox" onChange={getUserInput} />
            <br />

            <label htmlFor="sql">SQL</label>
            <input id="sql" value="SQL" type="checkbox" onChange={getUserInput} />
            <br />

            <ul>
                {courses.map((course) => (
                    <li>{course}</li>   
                ))
                }
            </ul>
        </div>
    )

}
export default Checkboxhandling;


Enter fullscreen mode Exit fullscreen mode

OUTPUT :

7. Dependent Dropdown

1.Country State City dropdown.

2.How will you structure state?

✓ Use an object or three separate states. An object structure like { country: '', state: '', city: '' }

3.When country changes, what should happen to state & city?

✓ When the country changes, you must reset the state and city values to empty strings or null. This prevents an invalid state/city combination from remaining selected for a new country.

CODE :

import { useState } from "react";

function CountryDropdown() {
    const [location, setLocation] = useState({
        country: "",
        state: "",
        city: "",
    });

    const handleCountry = (e) => {
        setLocation({
            country: e.target.value,
            state: "",
            city: "",
        })
    }

    const handleState = (e) => {
        setLocation({
            ...location,
            state: e.target.value,
            city: "",
        })
    }
    return (
        <div>
            <select value={location.country}
                onChange={handleCountry}>
                <option value="">Select Country</option>
                <option value="India">India</option>
                <option value="USA">USA</option>

                {/* <br /><br /> */}
            </select>

            <select value={location.state}
                onChange={handleState}>
                <option value="">Select State</option>


                {location.country === "India" && (
                    <>
                        <option value="Tamil Nadu">
                            Tamil Nadu
                        </option>

                        <option value="Kerala">
                            Kerala
                        </option>
                    </>

                )}
                {location.country === "USA" && (
                    <>
                        <option value="California">
                            California
                        </option>

                        <option value="Texas">
                            Texas
                        </option>
                    </>
                )}
            </select>
            {/* <br /><br /> */}

            <select value={location.city} onChange={(e) => setLocation({
                ...location, city: e.target.value,

            })}>
                <option value="">Select City</option>
                {location.state === "Tamil Nadu" && (
                    <>
                        <option value="Chennai">
                            Chennai
                        </option>

                        <option value="Coimbatore">
                            Coimbatore
                        </option>
                    </>
                )}

                {location.state === "Kerala" && (
                    <>
                        <option value="Kochi">
                            Kochi
                        </option>

                        <option value="Trivandrum">
                            Trivandrum
                        </option>
                    </>
                )}

                {location.state === "california" && (
                    <>
                        <option value="Los Angels">
                            Los Angels
                        </option>

                        <option value="san Diego">
                            san Diego
                        </option>
                    </>
                )}

                {location.state === "Texas" && (
                    <>
                        <option value="Houston">
                            Houston
                        </option>

                        <option value="Dallas">
                            Dallas
                        </option>
                    </>
                )}
            </select>

            <h3>Selected Location</h3>

            <p>Country:{location.country}</p>
            <p>State:{location.state}</p>
            <p>City:{location.city}</p>



        </div>
    )
}
export default CountryDropdown;

Enter fullscreen mode Exit fullscreen mode

OUTPUT :


Top comments (0)