1.1.0 • Published 3 years ago

html-form-component v1.1.0

Weekly downloads
3
License
ISC
Repository
gitlab
Last release
3 years ago

html-form-component

Little library to generate an HTML form and parse the request it submits. Based on html-encode-template-tag.

import html from 'encode-html-template-tag';
import form from 'html-form-component';

const nameForm = form(
	{
		method: 'POST'
	},
	html`<label>
		What's your name?
		<input name="name">
	</label>
	<button>Submit</button>
	`,
	params => params.get('name')
);

export default async (req, res) => {
	if(req.method==='POST') {
		const name = await nameForm.parse(req);

		res.end(await html`Your name is ${name}`.render());
		return;
	}

	res.end(await nameForm.render());
}

Constants

Functions

Typedefs

parser

Create a function for parsing form values from a request object. The new function will recieve the request object and retrieve the submitted form values as URLSearchParams. You can then supply a function for transforming these params before returning them.

ParamTypeDescription
parseParamsfunctionA function that accepts URLSearchParams and returns the parsed form values

form(attributes, body, parser) ⇒ FormElement

Creates a form element.

ParamTypeDescription
attributesObjectDict of attributes to add to the form element
body*Body of the form
parserfunctionFunction to transform the request body

parse(req) ⇒ URLSearchParams

Parse a request and return a URLSearchParams object

ParamTypeDescription
reqhttp.IncomingMessageThe request object to parse

FormElement

A representation of a form element, for rendering a form

ParamTypeDescription
renderfunctionGenerate the element as a string
parsefunctionGet the form data from a request object