jeudi 5 novembre 2020

How to set default value in checkbox and radio button?

I am making a simple react application where I have some default values to set to the input fields.

Here there are three input fields,

-> Textbox   = UserName

-> Checkbox  = Relocation

-> Radio     = ContactMode

Their respective values are,

 {
    UserName: "Test User",
    Relocation: true,
    ContactMode: "Email",
 }

Working Snippet:

const { useState } = React;

const App = () => {
  const [formValue, setFormValue] = useState({
    UserName: "Test User",
    Relocation: true,
    ContactMode: "Email",
  });

  const handleInputChange = (e) => {
    const { name, value } = event.target;
    setFormValue({
      ...formValue,
      [name]: value,
    });
  };
  
  const submitData = () => {
    console.log(formValue)
  }

  return (
    <div>
      <form>
        <label> User Name </label>
        <input
          type="text"
          name="UserName"
          value={formValue.UserName}
          onChange={handleInputChange}
        />
        <br />
        <br />
        <label> Willing to relocate? </label>
        <input
          type="checkbox"
          name="Relocation"
          value={formValue.Relocation}
          onChange={handleInputChange}
        />
        <br />
        <br />
        <label> Contact Mode </label>
        <input
          type="radio"
          name="ContactMode"
          value={`Email`}
          onChange={handleInputChange}
        />{" "}
        Email
        <input
          type="radio"
          name="ContactMode"
          value={`Text`}
          onChange={handleInputChange}
        />{" "}
        Text
        <input
          type="radio"
          name="ContactMode"
          value={`Both`}
          onChange={handleInputChange}
        />{" "}
        Both
        <br />
        <br />
        <button type="button" onClick={submitData}> Submit </button>
      </form>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Problem:

-> In the above eg.., Only the text field value is got set but checkbox and radio button values not got set by default.

Expectaion:

-> All the three input fields needs to get set by its default values.

-> On changing any input field and upon clicking submit button, the latest changes needs to get logged via formValue ..




Aucun commentaire:

Enregistrer un commentaire