티스토리 뷰
In React 18, when working with multiple custom components for an input tag using react-hook-form, you can follow a similar approach to the one used with regular input fields. Here's an example of how you can set it up:
First, create your custom input components:
// CustomInput.js
import React from 'react';
import styled from 'styled-components';
const StyledInput = styled.input`
/* your styles for the input */
`;
const CustomInput = React.forwardRef((props, ref) => (
<StyledInput {...props} ref={ref} />
));
export default CustomInput;
// CustomInputWithLabel.js
import React from 'react';
import styled from 'styled-components';
const StyledLabel = styled.label`
/* your styles for the label */
`;
const StyledInput = styled.input`
/* your styles for the input */
`;
const CustomInputWithLabel = React.forwardRef((props, ref) => (
<>
<StyledLabel htmlFor={props.id}>{props.label}</StyledLabel>
<StyledInput {...props} ref={ref} />
</>
));
export default CustomInputWithLabel;
In these examples, we create two custom input components: CustomInput
and CustomInputWithLabel
. The CustomInput
component is a simple styled input field, while CustomInputWithLabel
includes a label in addition to the input field.
Notice the use of React.forwardRef
to forward the ref
to the input element, allowing react-hook-form to interact with the input correctly.
Next, in your form component, you can use these custom inputs with react-hook-form:
import React from 'react';
import { useForm } from 'react-hook-form';
import CustomInput from './CustomInput';
import CustomInputWithLabel from './CustomInputWithLabel';
const MyForm = () => {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<CustomInput
type="text"
placeholder="Enter your name"
{...register('name')}
/>
<CustomInputWithLabel
type="email"
id="email"
label="Email"
{...register('email')}
/>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
In the MyForm
component, we use the register
function from react-hook-form to register our custom input components with the form. We spread the register
function's return value ({...register('name')}
and {...register('email')}
) onto our custom input components, just like we would with a regular input field.
This way, react-hook-form can correctly handle the form state and validation for these custom input components. You can customize the styles and behavior of your custom input components as needed, while still benefiting from the features provided by react-hook-form.
'개발' 카테고리의 다른 글
맥 에서 파일 / 디렉토리 (폴더) 구조 텍스트로 가져오기 (0) | 2017.08.17 |
---|---|
맥 에서 이클립스 실행 후 무한 로딩 상태로 멈춰있을때... (0) | 2016.07.07 |
CentOS7 에서 YUM 으로 MySQL 5.7 설치 시.. (0) | 2016.06.14 |
톰캣 파일 업로드 시 한글파일명 인코딩 문제 (0) | 2014.10.29 |