CoreUI + React Hook Form

Viewed 1719

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

import React from 'react';
import {
  CCard,
  CCardBody,
  CCardHeader,
  CCol,
  CRow,
  CForm,
  CFormGroup,
  CInput,
  CLabel,
  CValidFeedback,
  CInvalidFeedback,
  CSelect,
  CInputFile,
  CButton,
  CCardFooter
} from '@coreui/react';
import CIcon from '@coreui/icons-react';
import { useForm } from 'react-hook-form';

const defaultValues = {
  firstName: '',
  lastName: '',
  studentBadgeID: '',
  gender: '',
  dateOfBirth: '',
  class: '',
  religion: '',
  joiningDate: '',
  phone: '',
  admissionNumber: '',
  email: '',
  parentName: '',
  parentAddress: '',
  parentPhone: '',
  parentEmail: ''
};

const AddStudents = () => {
  const { register, handleSubmit, errors } = useForm(defaultValues);
  const onSubmit = data => console.log(data);

  return (
    <CCol xs="12">
      <CCard>
        <CForm onSubmit={handleSubmit(onSubmit)}>
          <CCardHeader>Add Student</CCardHeader>
          <CCardBody>
            <h4>Student Information</h4>
            <CRow className="my-0">
              <CCol lg="6" sm="12">
                <CLabel htmlFor="firstName">First Name</CLabel>
                <CInput
                  className="form-control-success"
                  id="firstName"
                  name="firstName"
                  ref={register({ required: true })}
                />
                <CInvalidFeedback className="help-block">
                  Please provide a valid information
                </CInvalidFeedback>
                <CValidFeedback className="help-block">
                  Input provided
                </CValidFeedback>
              </CCol>
            </CRow>
          </CCardBody>
          <CCardFooter>
            <CButton type="submit" size="sm" color="primary" className="mr-1">
              <CIcon name="cil-scrubber" /> Submit
            </CButton>
            <CButton type="reset" size="sm" color="danger">
              <CIcon name="cil-ban" /> Reset
            </CButton>
          </CCardFooter>
        </CForm>
      </CCard>
    </CCol>
  );
};

export default AddStudents;
2 Answers

Try

<Controller
  control={control}
  defaultValue={null}
  rules={{ required: true }}
  name="name"
  render={({ onChange, onBlur, value }) => (
    <CInput
      onChange={onChange}
      onBlur={onBlur}
      selected={value}
     />
   )}
 />

More Information: https://react-hook-form.com/api#Controller

Related