简体   繁体   中英

Cannot read property of 'touched' undefined

I'm using Formik to create forms in my React app, and using custom components as my Inputs, like so:

  <Field
    ...
    component={Input}
  />

However, when I use Input outside of a Formik form, I get the following error: Cannot read property of 'touched' undefined

My Input looks like this:

const Input = React.forwardRef(
  (
    { value, onChange, onKeyPress, placeholder, type, label, form: {touched, errors}, field, ...props },
    ref
  ) => (
      <div style={{ display: "flex", flexDirection: "column" }}>
        {label && (
          <label style={{ fontWeight: 700, marginBottom: `${scale.s2}rem` }}>
            {label}
          </label>
        )}
        <input
          ref={ref}
          style={{
            borderRadius: `${scale.s1}rem`,
            border: `1px solid ${color.lightGrey}`,
            padding: `${scale.s3}rem`,
            marginBottom: `${scale.s3}rem`
          }}
          value={value}
          onChange={onChange}
          onKeyPress={onKeyPress}
          placeholder={placeholder ? placeholder : "Type something..."}
          type={type ? type : "text"}
          {...field}
          {...props}
        />
        {touched[field.name] &&
          errors[field.name] && <div className="error">{errors[field.name]}</div>}
      </div>
    )
)

I'm not sure why touched should be undefined, seems it's conditionally rendered?

Link to Sandbox

Desired outcome: The Input should work both inside and outside of Formik.

How do I resolve this?

To make it work you have at least modify this line

<Input ref={"this.ref"} value={0} form={{}} />

And also this line

{touched && touched[field.name] && errors[field.name] && (

You're not passing form and touched as props to Input component, so they are undefined . You also not passing other props of Input component. So it can be good idea to review code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM