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>
);
}
<DataList
label='Select Chapter Number'
onSelect={changeChapterNumber}
options={chaptersFromSelectedComic}
/>
<DataList
label='Select Chapter Title'
onSelect={changeChapter}
options={chaptersFromSelectedComic}
swap={true}
/>
You've enclosed the list name (list="items"
) into the component, so all datalist options reference the same initially defined options.
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 />