Snippets (Serpiko)
About 6 minReact.jsSnippetsjsnodenodejsreactreactjsreactnativefacebookmetasnippets (Serpiko)
serpiko > react using state when you don't need it
react using state when you don't need it
input κ°μ μ
λ ₯λ°κ³ 보μ¬μ€ λ, useState
λ₯Ό μ¬μ©νμ§ μμλ λλ€
useState
λ₯Ό λ°°μ νλ―λ‘μ¨, 리λ λλ§ μμ¨ μ μλ€
import "./styles.css";
import { useState, useRef } from "react";
let renderCount = 0;
export default function App() {
const emailRef = useRef("");
const [inputResult, setInputResult] = useState("");
renderCount++;
function onSubmit(e) {
e.preventDefault();
setInputResult(emailRef.current.value);
console.log(emailRef.current.value);
}
return (
<>
<h4>Rerender Count: {renderCount}</h4>
<form onSubmit={onSubmit}>
<label htmlFor="email">Email</label>
<input
ref={emailRef}
type="email"
id="email"
onChange={() => {
console.log(emailRef);
}}
/>
<button type="submit">Submit</button>
<p>μ
λ ₯ν ν
μ€νΈ: {inputResult}</p>
</form>
</>
);
}
serpiko > React Hook Form: FormProvider-useFormContext
React Hook Form: FormProvider-useFormContext
- ContextAPIλ₯Ό μ΄μ©νμ¬
Sub.js
μμ μ¬μ©ν κ°μ App.js
μμλ κ°μ§κ° κ°λ₯νλ€
import { useState } from "react";
import { useForm } from "react-hook-form";
import Header from "./Header";
import Sub from "./Sub";
import "./styles.css";
import { useOrderFormContext } from "./FormProviders";
export default function App() {
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useOrderFormContext();
const [data, setData] = useState("");
return (
<div>
{}
<form onSubmit={handleSubmit((data) => setData(JSON.stringify(data)))}>
<Header />
{}
<label htmlFor="firstName">[App.js] First Name</label>
<input
{...register("firstName")}
id="firstName"
placeholder="First name"
/>
<label htmlFor="lastName">[App.js] Last Name</label>
{errors.lastName && <span>μνλ²³λ§ μ
λ ₯ν΄ μ£ΌμΈμ</span>}
<input
{...register("lastName", { pattern: /^[A-Za-z]+$/i })}
id="lastName"
placeholder="Last name (μνλ²³λ§ μ
λ ₯ν΄ μ£ΌμΈμ)"
/>
<label htmlFor="category">[App.js] category</label>
<select id="category" {...register("category")}>
<option value="">Select...</option>
<option value="A">Option A</option>
<option value="B">Option B</option>
</select>
{}
<label htmlFor="aboutYou">[App.js] aboutYou</label>
{}
{errors.aboutYou && (
<span>κ°μ μ
λ ₯ν΄ μ£ΌμΈμ (μ΅μ5μ, μ΅λ 20μ)</span>
)}
<textarea
id="aboutYou"
{...register("aboutYou", {
required: true,
minLength: 5,
maxLength: 20,
})}
placeholder="About you (μ΅μ5μ, μ΅λ 20μ)"
/>
<Sub />
<p>{data}</p>
<input type="submit" />
</form>
</div>
);
}
serpiko > React Hook Form (useState-less ν¨ν΄)
React Hook Form (useState-less ν¨ν΄)
- RHFμ λ΄μ₯λ
FormProvider
, useOrderFormContext
λ₯Ό μ΄μ©νμ¬ ContextAPIꡬν - Controlμ μ£Όμ
λ°μ μ»΄ν¬λνΈλ‘ λͺ¨λ μ»΄ν¬λνΈλ κ°μ useForm μμ± μμ κ³Ό μΌμΉ μν¨λ€
setValue
, resetField
, useWatch
μ΄μ©νμ¬ useState
μ 리λ λλ§ μμ΄ μλ°©ν₯ κ° νΈλ€λ§νκ³ μ°μ°- μ μΆ(Submit)μ, μ»΄ν¬λνΈμ μ μλ name κΈ°μ€μΌλ‘ κ°λ€μ λ°ννλ€
export default function App() {
return <h1>Hello world</h1>
}