create form react

 ==

created variables inputs and setinputs

in input value is varaible inputs.

on change call funciton 

call handlechange

setInputs(values => Object.assign({}, values, { [name]: value }));


assigne the values to this object


import { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
  const [inputs, setInputs] = useState({});

  const handleChange = (event) => {
    const name = event.target.name;
    const value = event.target.value;
    setInputs(values => ({...values, [name]: value}))
  }

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputs);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
      <input
        type="text"
        name="username"
        value={inputs.username || ""}
        onChange={handleChange}
      />
      </label>
      <label>Enter your age:
        <input
          type="number"
          name="age"
          value={inputs.age || ""}
          onChange={handleChange}
        />
        </label>
        <input type="submit" />
    </form>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);

=


=

ist mycar value loaded with volvo on page load normally it shows which one is ist value in drio down because of loaded value it showign as loaded value


function MyForm() {
  const [myCar, setMyCar] = useState("Volvo");

  const handleChange = (event) => {
    setMyCar(event.target.value)
  }

  return (
    <form>
      <select value={myCar} onChange={handleChange}>
        <option value="Ford">Ford</option>
        <option value="Volvo">Volvo</option>
        <option value="Fiat">Fiat</option>
      </select>
    </form>
  )
}



=

In this component:

  1. Initial Value:

    • myCar is initialized with "Volvo" using useState("Volvo"), so "Volvo" is the default value for the myCar state when the page first loads.
  2. Select Element:

    • The <select> element has a value prop set to myCar. Because myCar is initialized as "Volvo", the select dropdown will display "Volvo" as the selected option on page load.
  3. Changing the Selection:

    • When the user selects a different option, the handleChange function updates myCar to the selected option’s value, and the dropdown updates accordingly.

So, even though "Ford" is the first option in the list, "Volvo" will display as selected initially because myCar was set to "Volvo" on load. This behavior is expected and correct.

=





No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...