0
votes

I have created an input component to try avoid repetition of the bootstrap divs/classes. It looks like this:

import React from "react";
import "./Input.css";

const Input = ({ name, label, error, ...rest }) => {
  return (
    <div className="form-group">
      <label htmlFor={name}>{label}</label>
      <input
        {...rest}
        id={name}
        name={name}
        className="form-control form-control-lg"
      ></input>
      {error && <span className="input-error">{error}</span>}
    </div>
  );
};

export default Input;

Then on the form, I just call it like this:

<Input name="lastName label="Last Name" type="text" />

But because I want to use Formik I have to add the onBlur, onChange and error. But it is very repetitive to have to add those to each input. I have tried to add them into my Input component but I obviously get errors about useFormik not existing and I am a bit stuck. This is the input after adding formik

          <Input
            name="lastName"
            label="Last Name *"
            type="text"
            value={formik.values.lastName}
            onBlur={formik.handleBlur}
            onChange={formik.handleChange}
            error={formik.touched.lastName && formik.errors.lastName}
          />

I basically want to be able to add onBlur, onChange and error to the input component.

1

1 Answers

0
votes

You have to wrap your inputs with Formik as it injects context to React tree, then you will be able to use useField in your custom input component.