jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.99k stars 2.79k forks source link

[v2] Revisit `name` vs. `id` for Field / useField #1558

Open jaredpalmer opened 5 years ago

jaredpalmer commented 5 years ago

We should be consistent. The nice thing about using id is that you can stay DRY (and accessible) for a lot of inputs. I think that useField / Field should support both, with name taking precedence over id if both are specified. Below are some examples/cases (not exhaustive) to think about during this conversation.

Basic Examples

// Sibling <label>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" /> // if we support id, no need to write name prop

// Parent <label> (not impacted)
<label>First Name
  <Field id="firstName" /> 
</label>

<label>First Name
  <Field name="firstName" /> 
</label>

Other cases

Checkboxes

Based on the new behavior proposed in #1555

Boolean

// Sibling label
<Field type="checkbox" id="newsletter" />
<label htmlFor="newsletter">Get newsletter?</label>

// Parent label w/id
<label>
  <Field type="checkbox" id="newsletter" />
  Get newsletter?
</label>

// Parent label w/name
<label>
  <Field type="checkbox" name="newsletter" />
  Get newsletter?
</label>

Array-bound to checkbox group

// Sibling labels => { values:  { jobTypes: ["remote", "fulltime"] } }
<Field type="checkbox" id="remove-checkbox" value="remove" name="jobTypes" />
<label htmlFor="remote-checkbox">Remote</label>
<Field type="checkbox" id="fulltime-checkbox" value="fulltime" name="jobTypes" />
<label htmlFor="fulltime-checkbox">Full time</label>
falldowngoboone commented 5 years ago

In the array-bound checkbox group, what would happen if I put a value prop on the <Field>?

// Sibling labels => { values:  { jobTypes: ["remote", "fulltime"] } }
<Field type="checkbox" id="remove-checkbox" value="remove" name="jobTypes" />
<label htmlFor="remote">Remote</label>
<Field type="checkbox" id="fulltime-checkbox" value="fulltime" name="jobTypes" />
<label htmlFor="fulltime">Remote</label>

Should value take precedence over the id? I've run into this same problem while building some custom components for my teammates, and I've just kept putting off array checkboxes.

jaredpalmer commented 5 years ago

Good catch. name and value is required for the array bound checkbox and id is just for a11y. I updated my example