Hi Folks,
I'm trying to pass submitHandler as a props to a form component using the hooks based approach. How to access the form component state in the submitHandler function in the parent?
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import MyForm from "./myForm";
function App() {
useEffect(() => {});
const handleSubmit = e => {
e.preventDefault();
// How to access MyForm component's state here?
};
return (
<div>
<MyForm fname={"Arun"} lname={"Kumar"} onSubmit={handleSubmit} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Diego Bernal
Front-End Engineer
In this case,
<App/>should be the component that manages the state so that<MyForm/>uses it as props.Something like this:
const [firstName, setFirsName] = React.useState("Arun"); const [lastName, setLastName] = React.useState("Kumar"); // you'll need to define some event handlers to change the values // the form component will use these const handleSubmit = e => { e.preventDefault(); // do whatever you need to do with the values console.log("firstName", firstName); console.log("lastName", lastName); } return ( <div> <MyForm fname={firstName} lname={lastName} onSubmit={handleSubmit} /> </div> );