Skip to content

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 (
      <input type="text"
      onChange={(e) => setState(} />


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 (
      <form ref={nameForm}>
       <InputField label={'first name'} name={'firstname'}/>
       <InputField label={'last name'} name={'lastname'}/>
      <button onClick={handleClickEvent}>gett value</button>
render(<App />, document.getElementById('root'))

Working example: