Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Next.js how to get other Element event target value on button click

I have an input element and a button in React:

      <li><input type="text" placeholder="Enter new ID"></input>
      <button onClick={(e)=>this.saveKonfigElementHandler()}>Save</button></li>  

Now, when I enter some value into the input field, I want to save the value into some array when I click on the button. Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?

Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.

E.g:

<input type="text" value={this.state.inputFieldText.join('')} onChange={(event) => this.textHandler(event)}></input>

in the textHandler Method, I will save the target value from the input field into a Class Component state variable in the textHandler() method. And when I click the button, I retrieve that state value and can do some manipulation with it?

like image 537
Marc_L Avatar asked Oct 17 '25 09:10

Marc_L


1 Answers

A modern way to do it, with function components, hooks and a controlled form element, is:

import { useState } from 'react'

function MyComponent({ initialId, onSave }) {
  const [newId, setNewId] = useState(initialId)

  return (
    <li>
      <input 
        type="text" 
        placeholder="Enter new ID" 
        onChange={(e) => setNewId(e.target.value)} 
      />
      <button onClick={() => onSave(newId)}>Save</button>
    </li>
  )
}

I'd also note that it is considered better accessibility practice to use a label element for describing the purpose of your field, rather than a placeholder. Placeholders are more appropriate for example input.

like image 159
acjay Avatar answered Oct 18 '25 22:10

acjay