티스토리 뷰

개발

react-hook-form with multiple inputs

매미다 2024. 5. 8. 14:20

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.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
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
글 보관함