- Module intro
- What’s complex about forms
- Handling inputs & Forms with React
- Simplifications
- Our Starting Projects
- What’s so complex about forms?
- Forms and input can assume different states
- One or more inputs are invalid
- Output input specific error, massages & highlight problematic inputs
- Ensure form can’t be submitted/saved
- All inputs are valid
- All form to be submitted/saved
- One or more inputs are invalid
- When to validate
- When form is submitted
- Allow the user to enter valid value before warning him/her
- Avoid unnecessary warning but maybe present feedback “too late”
- When an input is losing focus
- Allow the user to enter valid value before warning him/her
- Very useful for untouched forms
- On every keystroke
- Warns user before he/she has a chance of entering valid values
- When form is submitted
- Forms and input can assume different states
- Dealing with Form submission & Getting user input values
- useRef
- import { useRef } from 'react'
- const nameInputRef = useRef()
- const formSubmissionHandle = event() => { event.preventDefault(); const enteredVal=nameInputRef.current.value console.log(enteredVal)}
- useState
- import { useState } from 'react'
- const [enteredName, setEnteredName] = useState('');
- const formSubmissionHandle = event() => { event.preventDefault(); if(enteredName.trim() === ‘’){ return; } console.log(enteredVal) setEnteredName('')}
- const nameInputChangeHandler = event => { setEnteredName(event.target.value)};
- useRef
- Adding basic validation
- Inside the formSubmissionHandle{ if(enteredName.trim() === ‘’){ return; }}
- Providing Validation Feedback
- const [enteredNameIsValid, setEnteredNameIsValid] = useState(true)
- In formSubmissionHandleif(enteredName.trim() === ''){ setEnteredNameIsValid(false) return;}
- Below the <input …./>{!enteredNameIsValid &&
Name must not be empty
}
- Handling the “Was touched” State
- Add another state variable const [enteredNameTouched, setEnteredNameTouched] = useState(false)
- React To Lost Focus
- const nameInputBlurHandler = event => { setEnteredNameTouched(true)};
- Managing the overall form Validity 1.
- Adding A custom input hook
- Create hooks folder in src
- Add hook
- User-input.js