단순 코드 기록/React

React_로그인폼(useState / useRef)

일일일코_장민기 2024. 3. 22. 12:41
728x90
import { useState } from "react";
export default function Login() {
  const [inputs, setInputs] = useState({
    email: "",
    password: "",
  });

  function handleInputChange(identifier, value) {
    setInputs({ ...inputs, [identifier]: value });
  }

  function handleSubmit(event) {
    event.preventDefault();
    console.log(inputs);
  }

  return (
    <>
      <h2>Login</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <div>
            <label htmlFor="email">email</label>
            <input
              type="email"
              id="email"
              name="email"
              value={inputs.email}
              onChange={(event) =>
                handleInputChange("email", event.target.value)
              }
            ></input>
          </div>
        </div>
        <div>
          <div>
            <label htmlFor="password">password</label>
            <input
              type="password"
              id="password"
              name="password"
              value={inputs.password}
              onChange={(event) =>
                handleInputChange("password", event.target.value)
              }
            ></input>
          </div>
        </div>
        <button type="submit">Login</button>
      </form>
    </>
  );
}

 

import { useRef } from "react";
export default function Login() {

  const email = useRef();
  const password = useRef();

  function handleSubmit(event) {
    event.preventDefault();
    const enteredEmail = email.current.value;
    const enteredPassword = password.current.value;
    console.log(enteredEmail, enteredPassword);
  }

  return (
    <>
      <h2>Login</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <div>
            <label htmlFor="email">email</label>
            <input
              type="email"
              id="email"
              name="email"
              ref={email}
            ></input>
          </div>
        </div>
        <div>
          <div>
            <label htmlFor="password">password</label>
            <input
              type="password"
              id="password"
              name="password"
              ref={password}
            ></input>
          </div>
        </div>
        <button type="submit">Login</button>
      </form>
    </>
  );
}

 

 

 

'단순 코드 기록 > React' 카테고리의 다른 글

React_유효성검사  (0) 2024.03.22
React_등록(FormData)  (0) 2024.03.22
React_Action함수를 이용한 Form 전송  (0) 2024.03.21
React_Error별 메세지 출력  (0) 2024.03.21
React_MainNavigation 로딩창  (0) 2024.03.21