Week 10/11 - Working with forms Lukáš Grolig et al. PB138 - Mo de rn Markup Language s and The ir Applicatio ns Outline Traditional forms React forms React-hook-form JSON Forms Basic form
Server-side handling Express.js form handling const { body, validationResult } = require('express-validator'); app.post( '/pet', // name must be at least 5 chars long, is trimmed and sanitized body('name').not().isEmpty().isLength({ min: 5 }).trim().escape(), (req, res) => { // Finds the validation errors in this request and wraps them in an object with handy func const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // Do something }, ); React form (the old way) class NameForm extends React.Component { // ... render() { return ( ); } } React form (the old way) class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { //... React Form using hook import React, { useState } from "react"; export function NameForm(props) { const [name, setName] = useState(""); const handleSubmit = (e) => { e.preventDefault(); alert(`Submitting Name ${name}`) } return ( React-hook-form import * as React from "react"; import { useForm } from "react-hook-form"; import Headers from "./Header"; export default function App() { const { register, handleSubmit } = useForm(); const onSubmit = (data) => alert(JSON.stringify(data)); return (