Forms
Forms in Preact work in the same way as they do in HTML & JS: you render controls, attach event listeners, and submit information.
Basic Form Controls
Often you'll want to collect user input in your application, and this is where <input>, <textarea>, and <select> elements come in. These elements are the common building blocks of forms in HTML and Preact.
Input (text)
To get started, we'll create a simple text input field that will update a state value as the user types. We'll use the onInput event to listen for changes to the input field's value and update the state per-keystroke. This state value is then rendered in a <p> element, so we can see the results.
class BasicInput extends Component {
state = { name: '' };
onInput = e => this.setState({ name: e.currentTarget.value });
render(_, { name }) {
return (
<div class="form-example">
<label>
Name: <input onInput={this.onInput} />
</label>
<p>Hello {name}</p>
</div>
);
}
}
Run in REPL
function BasicInput() {
const [name, setName] = useState('');
return (
<div class="form-example">
<label>
Name: <input onInput={e => setName(e.currentTarget.value)} />
</label>
<p>Hello {name}</p>
</div>
);
}
Run in REPL
Input (checkbox & radio)
class BasicRadioButton extends Component {
state = {
allowContact: false,
contactMethod: ''
};
toggleContact = () =>
this.setState({ allowContact: !this.state.allowContact });
setRadioValue = e => this.setState({ contactMethod: e.currentTarget.value });
render(_, { allowContact }) {
return (
<div class="form-example">
<label>
Allow contact: <input type="checkbox" onClick={this.toggleContact} />
</label>
<label>
Phone:{' '}
<input
type="radio"
name="contact"
value="phone"
onClick={this.setRadioValue}
disabled={!allowContact}
/>
</label>
<label>
Email:{' '}
<input
type="radio"
name="contact"
value="email"
onClick={this.setRadioValue}
disabled={!allowContact}
/>
</label>
<label>
Mail:{' '}
<input
type="radio"
name="contact"
value="mail"
onClick={this.setRadioValue}
disabled={!allowContact}
/>
</label>
<p>
You {allowContact ? 'have allowed' : 'have not allowed'} contact{' '}
{allowContact && ` via ${this.state.contactMethod}`}
</p>
</div>
);
}
}
Run in REPL
function BasicRadioButton() {
const [allowContact, setAllowContact] = useState(false);
const [contactMethod, setContactMethod] = useState('');
const toggleContact = () => setAllowContact(!allowContact);
const setRadioValue = e => setContactMethod(e.currentTarget.value);
return (
<div class="form-example">
<label>
Allow contact: <input type="checkbox" onClick={toggleContact} />
</label>
<label>
Phone:{' '}
<input
type="radio"
name="contact"
value="phone"
onClick={setRadioValue}
disabled={!allowContact}
/>