how to get input field value on button click in react?
Use
<form>
tag withuseRef
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
You could always lift up the state in parent component. codeSandbox link
Parent Component
import React from "react";
import ReactDOM from "react-dom";
import ChildComponent from "./Child";
const { useState } = React;
function App() {
const [first_name, setFirstName] = useState("");
const [last_name, setLastName] = useState("");
const handleFirstNameChange = ({ target }) => {
setFirstName(target.value);
};
const handleLastNameChange = ({ target }) => {
setLastName(target.value);
};
const handleClick = () => {
console.log(first_name);
console.log(last_name);
};
return (
<div className="App">
<ChildComponent
label="first name"
onChange={handleFirstNameChange}
value={first_name}
/>
<ChildComponent
label="last name"
onChange={handleLastNameChange}
value={last_name}
/>
<button onClick={handleClick}>Click me</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Child Component
import React from "react";
const ChildComponent = ({ label, onChange, value, name }) => {
return (
<div>
<label>{label}</label>
<input type="text" value={value} name={name} onChange={onChange} />
</div>
);
};
export default ChildComponent;
You could always combine onChange handler for first name and last name.
Hope that helps!!!