Search code examples
reactjsreact-hooksreact-key-index

how to define keys within div class of react elements?


I am working on a form in react-Js as a beginner. During debugging I came to know the problem could be not defining the unique keys for every field in the form. I am not able to see the values changing in the field when adding new records in the form. here is my code for fields

const AddTask = ({ onAdd, selectedTask,isReadOnly }) => {
  console.log("selectedTask",selectedTask);
  const [dte, setdte] = useState("");
  const [rmk, setrmk] = useState("");
  const [isChecked, setIsChecked] = useState(false);
  const onSubmit = (e) => {
    const data = {
      dte,
      rmk,
    }
    onAdd(data); 
    setdte("");  
    setrmk("");
  };
return (
<form className="add-form" onSubmit={onSubmit}>
              <div className="form-group row">
                <label className="col-sm-2 col-form-label">Date </label>
                <div className="col-sm-8">
                  <input
                    className="form-control"
                    type="Date"
                    placeholder="Add"
                    value={selectedTask?.dte || ""}
                    onChange={(e) => setdte(e.target.value)}
                    //ref={dteRef}
                    disabled={isReadOnly}
                  />
                </div>
              </div>
              <div className="form-group row">
                <label className="col-sm-2 col-form-label">Remarks </label>
                <div className="col-sm-8">
                  <input
                    className="form-control"
                    type="text"
                    value={selectedTask?.rmk || ""}
                   // ref={rmkRef}
                    onChange={(e) => setrmk(e.target.value)}
                    disabled={isReadOnly}
                  
                  />
                </div>
              </div>

Solution

  • it have nothing to do with defining keys we just have to change the priority of condition in value as:

    value={ dte ||selectedTask?.dte }
    value={ rmk || selectedTask?.rmk} 
    

    for all input fields it will solve the problem