0
votes

I have a dropdown Select component. This component displays the values of the elements, that we get from the server. In the following schema:

[
  {label: 1, value: 1},
  {label: 2, value: 2},
  {label: 3, value: 3},
]

I am using Formik and map through the data, to get the values. Problem is, that I don't have a placeholder value, thus users think the value is already selected.

I am reading through the formik examples and I am not founding anything similar.

Here is a working example, from the formik examples

I am trying to force the placeholder, as an option, but that doesn't work. Any ideas?

          <div className="py-3">
              <label>
                <span className="font-weight-bold">Select Group</span>
                <span className="text-danger">*</span>
              </label>
              <Field
                name="group"
                component="select"
                placeholder="Select Group (Just one)"
                className={classNames('form-control', {
                  'is-invalid': errors.group && touched.group
                })}
              >
                {groups.map(group => (
                  <option key={group.label} value={group.value}>
                    {group.value}
                  </option>
                ))}
              </Field>
              {errors.group && touched.group ? (
                <div className="text-danger">{errors.group}</div>
              ) : null}
            </div>

Currently, the groups have initial value of the first item returned from the server.

I want to display the placeholder, like in the code above. This one placeholder="Select Group (Just one)"

1

1 Answers

7
votes

Apparently, there are a lot of ways to do this. I chose the easiest one. I just added a defaultValue tag in a second option field. This allows the default value to be displayed and you can choose through the mapped options on render dropdown:

Like this:

<div className="py-3">
              <label>
                <span className="font-weight-bold">Select Group</span>
                <span className="text-danger">*</span>
              </label>
              <Field
                name="group"
                component="select"
                className={classNames('form-control', {
                  'is-invalid': errors.group && touched.group
                })}
              >
                <option defaultValue>Select Group (Just one)</option>
                {groups.map(group => (
                  <option key={group.label} value={group.value}>
                    {group.value}
                  </option>
                ))}
              </Field>
            </div>