Home > Mobile >  How to solve Uncontrolled Component problem in React with Function Component?
How to solve Uncontrolled Component problem in React with Function Component?

Time:11-05

I was making Form components.(It is Function Component) It is Uncontrolled Component, because I don't want unnecessary render in Input components. But it has unexpected word.

  1. I try to set value with setState() in Input Component and get through value props onChange. It is not pass whole value from Input to Form

  2. I don't want unnecessary rendering. However, when I enter value in email, react rendering with password at the same time.

How can I solve this problem?

Code Sand Box Link Edit makeWellDoneComponents (forked)

Form component:

const Form = () => {
  const email = useRef(null);
  const password = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    console.log(email.current.value, password.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <Input type="email" placeholder="이메일" ref={email} />
      <Input type="password" placeholder="비밀번호" ref={password} />
      <button type="submit">가입</button>
      <button type="reset">초기화</button>
    </form>
  );
};

export default Form;

Input component:

import React, { forwardRef } from "react";

const Input = forwardRef((props, ref) => {
  return <input {...props} ref={ref} />;
});
  • Related