'Selecting value of inputs in react
I have an issue with a project i am working on where i want o select the value of an input element and save it. When ii write my code and console log it to see if it will get the correct value it always just give the value of the first value. I have my inputs in a parent element and i have 5 of them. this is my code:
<div className="number--container">
<input type="button" value="1" onClick={btnClicked}></input>
<input type="button" value="2" onClick={btnClicked}></input>
<input type="button" value="3" onClick={btnClicked}></input>
<input type="button" value="4" onClick={btnClicked}></input>
<input type="button" value="5" onClick={btnClicked}></input>
this is the function that handles the value retrieving:
function btnClicked(){
const value= document.querySelector("input").value
console.log(value)
}
Solution 1:[1]
function btnClicked(e){
const value= e.target.value;
console.log(value)
}
In react, html element should not be approached directly. If you want direct access, we recommend using "ref". https://reactjs.org/docs/refs-and-the-dom.html
Solution 2:[2]
Normally in react we never use the plain javascript DOM manipulation api such querySelector;
function btnClicked(event){
const {value}= event.target;
console.log(value)
}
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 | |
| Solution 2 | Hamza Sehouli |
