Skip to content

Instantly share code, notes, and snippets.

@jagsbyteinception
Created July 16, 2021 13:57
Show Gist options
  • Save jagsbyteinception/c23ed86a1fa11113349e1181c7e6631a to your computer and use it in GitHub Desktop.
Save jagsbyteinception/c23ed86a1fa11113349e1181c7e6631a to your computer and use it in GitHub Desktop.
//common state for different inputs
function RegisterYourCatForm() {
const [values, setValues] = useState({
name: '', color: '', age: '', habits: ''
});
const set = name => {
return ({ target: { value } }) => {
setValues(oldValues => ({...oldValues, [name]: value }));
}
};
return (
<form>
<h2>Register Your Cat</h2>
<label>Name*:</label>
<input value={values.name} onChange={set('name')} />
<label>Color*:</label>
<select value={values.color} onChange={set('color')}>
<option value="">Select color</option>
{COLORS.map(c => <option key={c}>{c}</option>)}
</select>
<label>Age*:</label>
<input value={values.age} onChange={set('age')} />
<label>Habits:</label>
<textarea value={values.habits} onChange={set('habits')} />
<button type="submit">Submit</button>
</form>
);
}
@jagsbyteinception
Copy link
Author

   //with validation and fill fields if data passed
const [values, setValues] = useState(
	{
		firstname: "", lastname: ""
		...props.data, //overwrites above fields if passed
		firstnameInvalid: "", lastnameInvalid: ""
	}
)

const onChange = (event, id, value) => {
	setValues(oldValues => ({ ...oldValues, [id]: value }))
	if (id.indexOf('Invalid') == -1) { //not setting validation msg. clear old msg
		setValues(oldValues => ({ ...oldValues, [`${id}Invalid`]: '' }))
	}
}

const onFormSubmit = (e) => {
	e.preventDefault()
	if (values.firstname > values.lastname) { //do custom validation
		onChange(null, 'startDateInvalid', "Start date should be equal or less than end date") //code simplyify: showing err msg only on start date and not end date 
		return false
	}
	
	//validation passed. clear all invalid errors
	for (const [key, value] of Object.entries(values)) {
		key.indexOf('Invalid') >= 0 && value && setValues(oldValues => ({ ...oldValues, [key]: '' }))
	}
	//submit done
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment