Search code examples
javascriptreactjsreact-propsconditional-operator

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


My code is written with React and I am trying to conditionally swap what gets assigned to value in each element. swap is being passed in as a prop and I thought it would work to act as the trigger but I get no change when I use swap=true vs swap=null.

function DataList({label, onSelect, options, swap}) {

    return (
        <DataListContainer>
            <CustomInput placeholder={label} list="items" name="item" id="item" required onChange={onSelect}></CustomInput>
            <datalist id='items' >
                {options? options.map(option => <option key={option.number} value={swap ? option.title : option.number}>{swap ? option.number : option.title}</option>) : null}
            </datalist>
        </DataListContainer>
    );
}
Here is the code that's actually rendering my component.

<DataList 
  label='Select Chapter Number' 
  onSelect={changeChapterNumber} 
  options={chaptersFromSelectedComic}
/>
<DataList 
  label='Select Chapter Title' 
  onSelect={changeChapter} 
  options={chaptersFromSelectedComic} 
  swap={true}
 />


Solution

  • 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