일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 리액트
- 클래스 추가하기 #특정 url 클래스 추가 #사이트 접속시 클래스 추가 #오공완 #javascript
- 리스트랜더링
- 오공완
- React
- 오공완 #리액트 공부 #React
- map()에는 key값이 필요
- Today
- Total
new_bird-hyun
React에서 React Hook Form과 Context API로 전역 폼 상태 관리 본문
// FormContext.js
import React, { createContext, useContext } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
const FormContext = createContext();
export const FormProviderComponent = ({ children }) => {
const methods = useForm();
return (
<FormContext.Provider value={methods}>
<FormProvider {...methods}>{children}</FormProvider>
</FormContext.Provider>
);
};
export const useFormContext = () => useContext(FormContext);
// Form.js
import React from 'react';
import { useFormContext } from './FormContext';
const FormInput = ({ name, label }) => {
const { register, formState: { errors } } = useFormContext();
return (
<div>
<label>{label}</label>
<input {...register(name, { required: `${label}을 입력하세요.` })} />
{errors[name] && <p>{errors[name].message}</p>}
</div>
);
};
export default function Form() {
const { handleSubmit } = useFormContext();
const onSubmit = (data) => {
console.log('폼 데이터:', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<FormInput name="name" label="이름" />
<FormInput name="email" label="이메일" />
<button type="submit">제출</button>
</form>
);
}
// App.js
import React from 'react';
import { FormProviderComponent } from './FormContext';
import Form from './Form';
function App() {
return (
<FormProviderComponent>
<Form />
</FormProviderComponent>
);
}
export default App;
// React Hook Form과 Context API를 결합하면 복잡한 폼 상태 관리를 간소화할 수 있음
'코딩 공부' 카테고리의 다른 글
React에서 Suspense와 Error Boundary로 안정적인 비동기 처리 (0) | 2025.01.04 |
---|---|
React에서 동적 폼 필드 관리 (0) | 2025.01.03 |
React.memo와 React Profiler로 성능 분석 및 최적화 (0) | 2025.01.01 |
React에서 Context API와 Selector로 성능 최적화 (0) | 2024.12.31 |
React에서 Optimistic Updates 구현하기 (0) | 2024.12.30 |