Home > other >  Selecting value of inputs in react
Selecting value of inputs in react

Time:04-29

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)
}

CodePudding user response:

 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

CodePudding user response:

Normally in react we never use the plain javascript DOM manipulation api such querySelector;

 function btnClicked(event){
  const {value}= event.target;
  console.log(value)
}
  • Related