Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Default value doesn't get updated inside input

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

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!