In a list of certain records where I'm populating in the dropdown of an input component. The default value is set on page loading but, I need to update it on click event of a button. Refer to the code below.
Home.js
const allList = [
{ id: "1", value: "Fruits" },
{ id: "2", value: "Vegetables" },
{ id: "3", value: "Grains" },
{ id: "4", value: "Milk" },
{ id: "5", value: "Meat" },
{ id: "6", value: "Fish" },
{ id: "7", value: "Pulses" }
];
const [itemList, setItemList] = useState(allList);
const [newValue, setNewValue] = useState(allList[0].value)
// I want to set the value on click of cancel button
const handleCancel = (e) => {
setNewValue(allList[2].value)
setPopup(false);
};
return (
<>
<DataList
defaultValue={newValue}
list="itemListOptions"
id="itemList"
placeholder="Search/select items"
data={itemList}
onSelectionChange={itemChanged}
></DataList>
{popup === true ? (
<Popup okbtnClick={handleOK} canclebtnclick={handleCancel} />
) : null}
</>
)
DataList.js
<input
defaultValue={props?.defaultValue ?? ""}
className="form-control cpselect"
id={props?.id ?? ""}
list={props?.list ?? ""}
placeholder={props?.placeholder ?? ""}
onChange={props?.onSelectionChange ?? ""}
/>
<datalist key={props.id} id={props?.list ?? ""}>
{props.data.map((d) => {
return <option key={d.id} id={d.id} value={d.value}></option>;
})}
</datalist>
My intention is to change the defaultValue inside the input field, on click of cancel button. Here it loads the first element and on click event should load third element. What is the best optimal solution?
Please refer to the Codesandbox link: https://codesandbox.io/s/clever-rumple-ig0wwj
What you want to do is to use value instead of defaultValue.
defaultValue property is configured in such a way that it reads the prop only once and then creates an inner state that handles changes.