Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // controlled form
- import React, { useState } from 'react';
- import './App.css';
- import cn from 'classnames';
- interface FormDataProps { username: string, email: string, subscribe: string }
- const INITIAL_FORM: FormDataProps = { username: '', email: '', subscribe: 'none' };
- function App() {
- const [formData, setFormData] = useState<FormDataProps>(INITIAL_FORM)
- const [dirty, setDirty] = useState<boolean>(false);
- function onSubmitHandler(event: React.FormEvent<HTMLFormElement>) {
- event.preventDefault();
- console.log(formData)
- setFormData(INITIAL_FORM)
- }
- function onChangeHandler(e: React.ChangeEvent<!!|>) {
- setFormData({
- ...formData,
- [e.currentTarget.name]: e.currentTarget.value
- })
- setDirty(true);
- }
- const isUsernameValid = formData.username.length > 2
- const isEmailValid = formData.email.length > 2;
- const valid = isUsernameValid && isEmailValid;
- return <div className="centered">
- {!valid && dirty && 'form wrong'}
- <form onSubmit={onSubmitHandler}>
- <input
- className={cn(
- 'form-control',
- { 'is-invalid': !isUsernameValid && dirty }
- )}
- type="text"
- value={formData.username}
- onChange={onChangeHandler}
- name="username"
- />
- <input
- type="text"
- className={cn(
- 'form-control',
- { 'is-invalid': !isEmailValid && dirty }
- )}
- value={formData.email}
- onChange={onChangeHandler}
- name="email"
- />
- <select value={formData.subscribe} onChange={onChangeHandler} name="subscribe">
- <option value="none">Select your choice</option>
- <option value="yes">yes</option>
- <option value="no">no</option>
- </select>
- <button type="submit" disabled={!valid}>save</button>
- </form>
- </div>
- }
- export default App;
Add Comment
Please, Sign In to add comment