DEV Community

govindbisen
govindbisen

Posted on

2 2

Code reference form input with useReducer

The code runs in App.js

you can write Reducer function elsewhere to shorten you App component.
code will run fine.

I often suffer from lack of written working code for reference, hence I am making it.

we will use useReducer hook from react function component to handle multiple input.

Also find the logic for radio button how you handle initial value for radio button.

import { useReducer } from "react";

export default function App() {
  const formReducer = (state, action) => {
    switch (action.type) {
      case "HandleInputText": {
        return {
          ...state,
          [action.field]: action.payload
        };
      }
      case "ToggleConsent": {
        return {
          ...state,
          hasConsented: !state.hasConsented
        };
      }
      default:
        return state;
    }
  };

  const initialState = {
    username: "",
    email: "",
    password: "",
    hasConsented: false,
    gender: "male"
  };

  const [formState, dispatch] = useReducer(formReducer, initialState);
  console.log(formState);
  // where dispatch is a method to trigger state updates/changes, reducer is a function we define which controls how we change the state, and initial state is an object with initial values defined, like the initialFormState example above.
  const handleChange = (e) => {
    dispatch({
      type: "HandleInputText",
      field: e.target.name,
      payload: e.target.value
    });
  };

  return (
    <div className="App">
      <h1> Reducer with form </h1>
      <label>User Name </label>
      <input
        type="text"
        name="username"
        value={formState.username}
        onChange={(e) => handleChange(e)}
      />{" "}
      <br />
      <label>Email </label>
      <input
        type="text"
        name="email"
        value={formState.email}
        onChange={(e) => handleChange(e)}
      />
      <br />
      <label>Password </label>
      <input
        type="text"
        name="password"
        value={formState.password}
        onChange={(e) => handleChange(e)}
      />
      <br />
      <label>Gender </label>
      <div onChange={(e) => handleChange(e)}>
        <input
          type="radio"
          value="Male"
          name="gender"
          checked={formState.gender === "male"}
        />{" "}
        Male
        <input
          type="radio"
          value="Female"
          name="gender"
          checked={formState.gender === "female"}
        />{" "}
        Female
        <input type="radio" value="Other" name="gender" /> Other
      </div>
      <br />
      <label> i hearby Govind declare this that the code runs in react App </label>
      <input
        type="checkbox"
        checked={formState.hasConsented}
        onChange={() => dispatch({ type: "ToggleConsent" })}
      />
      <button onClick={() => console.log("printing", formState)}>
        print on console
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

working code here
https://codesandbox.io/s/usereducerwithform-ubrz4m?file=/src/App.js:0-2542

you can see warning also, please help me solve that warning.

code is self explanatory but still if you want to understand you can talk to me, my whatsapp 8823011424
if you want to donate me please do 8823011424@upi no more than 1 rupee.

Regards
Govind

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay