If I want to make a functional component that will contain a form ,to login for example, and I want to contain the state in App component and Login will be its child, can I mutate the state in App using the form in Login child?
In most cases, we recommend using controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
Forms are an integral part of any modern web application. It allows the users to interact with the application as well as gather information from the users.
import React, {useState} from 'react';
function Submit() {
const [inputField , setInputField] = useState({
first_name: '',
last_name: '',
gmail: ''
})
const inputsHandler = (e) =>{
setInputField( {[e.target.name]: e.target.value} )
}
const submitButton = () =>{
alert(inputField.first_name)
}
return (
<div>
<input
type="text"
name="first_name"
onChange={inputsHandler}
placeholder="First Name"
value={inputField.first_name}/>
<br/>
<input
type="text"
name="last_name"
onChange={inputsHandler}
placeholder="First Name"
value={inputField.last_name}/>
<br/>
<input
type="gmail"
name="gmail"
onChange={inputsHandler}
placeholder="Gmail"
value={inputField.gmail}/>
<br/>
<button onClick={submitButton}>Submit Now</button>
</div>
)
}
export default Submit
Yes. Pass two props an object data
and a method onChange
to Login
from App
.
data
will set the values for the form in Login
.
Fire onChange
with updated form values if there is any change in Login
form.
Handle it in App
and update its state which will then flow down to Login
as data
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With