Search code examples
reactjsdropdownbootstrap-5formik

How to resolve "A control must be associated with a text label" on a datalist's option?


Building a dropdown and referencing Bootstrap 5 docs' on Datalists it shows an example of:

<label for="exampleDataList" class="form-label">Datalist example</label>
<input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
<datalist id="datalistOptions">
  <option value="San Francisco">
  <option value="New York">
  <option value="Seattle">
  <option value="Los Angeles">
  <option value="Chicago">
</datalist>

Writing my component to handle drop downs I'm unsure how to resolve the ESLint error of:

A control must be associated with a text label

code:

import React from 'react'
import PropTypes from 'prop-types'
import { Field } from 'formik'

const Drop = ({ name, label, id, placeholder, options }) => {
  return (
    <div className="form-group mb-4">
      <label htmlFor={name}>{label}:</label>
      <Field
        aria-label={`${name}-dropdown`}
        name={name}
        className="form-control"
        list={id}
        id={`${id}DropDown`}
        placeholder={placeholder}
      />
      <datalist id={id}>
        {options.map((option, key) => (
          <option key={key} value={option.toString()} data-value={option.toString()} />
        ))}
      </datalist>
    </div>
  )
}

Drop.propTypes = {
  name: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  placeholder: PropTypes.string.isRequired,
  options: PropTypes.array.isRequired,
}

export default Drop

Research

In my option how can I resolve the ESLint error?


Solution

  • I was able to resolve my issue by adding an aria-label to the option so this:

    <datalist id={id}>
      {options.map((option, key) => (
        <option key={key} value={option.toString()} data-value={option.toString()} />
      ))}
    </datalist>
    

    turned into:

    <datalist id={id}>
      {options.map((option, key) => (
        <option key={key} value={option.toString()} aria-label={option.toString()} data-value={option.toString()} />
      ))}
    </datalist>
    

    after going through the docs and finding control-has-associated-label.