Ternary operator fails when used to set value of datalist option in React component

Issue

You’ve enclosed the list name (list="items") into the component, so all datalist options reference the same initially defined options.

Solution

Expose out list attribute as a prop so each DataList component can specify its own set of options.

function DataList({
  label,
  list, // <-- add list prop
  onSelect,
  options,
  swap
}) {
  return (
    <DataListContainer>
      <CustomInput
        placeholder={label}
        list={list} // <-- set list attribute for input
        name="item"
        id="item"
        required
        onChange={onSelect}
      ></CustomInput>
      <datalist id={list}> // <-- set id for datalist options
        {options
          ? options.map((option) => (
              <option
                key={option.number}
                value={swap ? option.title : option.number}
              >
                {swap ? option.number : option.title}
              </option>
            ))
          : null}
      </datalist>
    </DataListContainer>
  );
}

Pass a list prop to each DataList component.

<DataList list="itemsA" label="List A" options={options} />
<DataList list="itemsB" label="List B" options={options} swap />

Edit ternary-operator-fails-when-used-to-set-value-of-datalist-option-in-react-compon

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top