'Get the last value of the onChange function
//let's say these are the 3 variables i got from the text
const varArray = ['montant', 'test','date']
//and here is where i want to store the name of the variable and the value the user typed in the
//text field
const [variableValues, setVariableValues] = useState([{name: '', value: ''}]);
//this is the what i m doing in order to solve the given problem
{
varArrayCopy.map(
variable =>
<TextField
key={variable}
margin="dense"
label={variable}
fullWidth
variant="standard"
onChange={e => setVariableValues([...variableValues, {name: variable, value: e.target.value}])}
/>
)
}
i m sending back the data in an alert (after i click on the "send" button) and the result i m getting is this
Solution 1:[1]
It appears like that because you used onChange prop. Each keystroke renders a change to your variableValues state thus adding a object letter by letter. What you can do is use the useRef hook for your Text fields in order to get the values. You could create an array named inputRefs which would store these refs & just loop through them through your varArrayCopy.map
const montant = useRef(null);
const test = useRef(null);
const date = useRef(null);
const inputRefs = [montant, test, date]
{
varArrayCopy.map(
(variable, index) =>
<TextField
key={variable}
margin="dense"
label={variable}
fullWidth
variant="standard"
ref={inputRefs[index]}
onChange={e => setVariableValues([...variableValues, {name: variable, value: inputRefs[index].current}])}
/>
)
}
Lastly, remove the onChange variable and add the setVariableValues to your Send button function. Also refactor it like
setVariableValues([...variableValues, {name: variable,value:inputRefs[index].current}
This will get the current value inside the text box. Hope this would help brother. Refer to docs: https://reactjs.org/docs/hooks-reference.html#useref
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MLDC |
