Search code examples
javascriptreactjs

how to get input field value on button click in react?


Could you please tell me how to get input field value on button click in react , I am using react hooks .I want to get first name and lastname value on button click. I already pass name attribute in my function component.

Here is my code

import React, { Component, useState } from 'react';
import { render } from 'react-dom';

export default function InputField({name,label}) {
  const [state, setState] = useState('')
  return (
    <div>
     <label>{label}</label>
      <input type="text" 
      value={state} 
      name={name}
      onChange={(e) => setState(e.target.value)} />

      {state}
    </div>
  );

}

Solution

  • Use <form> tag with useRef hook

    Wrap your <InputField> tags with an html <form> tag and put a react ref on the later. Like this:

    import React, { Component, useRef } from 'react'
    import { render } from 'react-dom'
    
    import InputField from './inputfield'
    
    import './style.css'
    
    function App () {
      const nameForm = useRef(null)
    
      const handleClickEvent = () => {
         const form = nameForm.current
         alert(`${form['firstname'].value} ${form['lastname'].value}`)
      }
    
      return (
        <div>
          <form ref={nameForm}>
           <InputField label={'first name'} name={'firstname'}/>
           <InputField label={'last name'} name={'lastname'}/>
          </form>
          <button onClick={handleClickEvent}>gett value</button>
        </div>
      )
    }
    
    render(<App />, document.getElementById('root'))
    

    Working example: https://stackblitz.com/edit/react-shtnxj