No need to write change handlers for multiple React inputs!

nas5w

Nick Scialli (he/him)

Posted on March 17, 2020

No need to write change handlers for multiple React inputs!

No need to write change handlers for multiple React inputs! You can create a function that takes both the prop name and the value as arguments. If using Typescript, use generics to narrow the type of the value based on the prop.

type User = {
  name: string;
  age: number;
  admin: boolean;
};

function App() {
  const [user, setUser] = useState<User>(defaultUser);

  const setUserProp = <P extends keyof User>(prop: P, value: User[P]) => {
    setUser({ ...user, [prop]: value });
  };

  return (
    <div>
      <input
        onChange={e => {
          setUserProp("name", e.target.value);
        }}
      ></input>
      <input
        onChange={e => {
          setUserProp("age", parseInt(e.target.value));
        }}
      ></input>
      <input
        onChange={() => {
          setUserProp("admin", !user.admin);
        }}
      ></input>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
nas5w
Nick Scialli (he/him)

Posted on March 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related