Skip to content

Instantly share code, notes, and snippets.

@JinsupJung
Created April 22, 2023 07:25
Show Gist options
  • Save JinsupJung/80c39084c6085ac5bd14a638acf0c9b5 to your computer and use it in GitHub Desktop.
Save JinsupJung/80c39084c6085ac5bd14a638acf0c9b5 to your computer and use it in GitHub Desktop.
[리액트 useRef] #React
import React, { useState, useRef } from "react";
import Card from "../UI/Card";
import Button from "../UI/Button";
import ErrorModal from "../UI/ErrorModal";
import Wrapper from "../Helpers/Wrapper";
import styles from "./UserInput.module.css";
const UserInput = (props) => {
const nameInputRef = useRef();
const ageInputRef = useRef();
const [error, setError] = useState();
const addUserHandler = (event) => {
event.preventDefault();
const enteredName = nameInputRef.current.value;
const enteredUserAge = ageInputRef.current.value;
if (enteredName.trim().length === 0 || enteredUserAge.trim().length === 0) {
setError({
title: "Invalid input",
message: "Please enter a valid name and age (non-empty values).",
});
return;
}
if (+enteredUserAge < 1) {
setError({
title: "Invalid age",
message: "Please enter a valid age (> 0).",
});
return;
}
const formData =
{
name: nameInputRef.current.value,
age: ageInputRef.current.value,
}
;
props.onAddUser(formData);
nameInputRef.current.value = "";
ageInputRef.current.value = "";
};
const errorHandler = () => {
setError(null);
};
return (
<Wrapper>
{error && (
<ErrorModal
title={error.title}
message={error.message}
onConfirm={errorHandler}
/>
)}
<Card className={`${styles["form-control"]}`}>
<form onSubmit={addUserHandler}>
<label htmlFor="username">Username</label>
<input id="username" type="text" ref={nameInputRef} />
<label htmlFor="age">Age (Years)</label>
<input id="age" type="number" ref={ageInputRef} />
<Button type="submit">Add User</Button>
</form>
</Card>
</Wrapper>
);
};
export default UserInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment