diff --git a/docs/components/form.md b/docs/components/form.md index 0dceb1cee..9293a2813 100644 --- a/docs/components/form.md +++ b/docs/components/form.md @@ -30,14 +30,11 @@ Shoelace forms don't make use of `action` and `method` attributes and they don't ``` @@ -78,15 +61,12 @@ import { } from '@shoelace-style/shoelace/dist/react'; function handleSubmit(event) { - const formData = event.detail.formData; let output = ''; - // - // Example 1: Post data to a server and wait for a JSON response - // + // Post data to a server and wait for a JSON response fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', - body: formData + body: event.detail.formData }) .then(response => response.json()) .then(result => { @@ -95,20 +75,6 @@ function handleSubmit(event) { .catch(error => { console.error('Error:', error); }); - - // - // Example 2: Output all form control names + values - // - for (const entry of formData.entries()) { - output += `${entry[0]}: ${entry[1]}\n`; - } - alert(output); - - // - // Example 3: Get all form controls that were serialized as - // an array of HTML elements - // - console.log(event.detail.formControls); } const App = () => ( @@ -130,6 +96,79 @@ const App = () => ( ); ``` +## Handling Submissions + +### Using Form Data + +On submit, a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object will be attached to `event.detail.formData`. You can use this along with [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) to pass data to the server. + +```html preview + + + +
+ Submit +
+ + +``` + +```jsx react +import { + SlButton, + SlForm, + SlInput +} from '@shoelace-style/shoelace/dist/react'; + +const App = () => { + function handleSubmit(event) { + fetch('https://jsonplaceholder.typicode.com/posts', { + method: 'POST', + body: event.detail.formData + }).then(res => { + console.log(res); + }).catch(err => { + console.error(err); + }); + } + + return ( + + + +
+ Submit +
+ ); +}; +``` + +### Converting Form Data to JSON + +It's sometimes useful to have form values in a plain object or a JSON string. You can convert the submitted `FormData` object to JSON by iterating and placing the name/value pairs in an object. + +```js +form.addEventListener('sl-submit', event => { + const json = {}; + event.detail.formData.forEach((value, key) => (json[key] = value)); + + console.log(JSON.stringify(json)); +}); +``` + ## Form Control Validation Client-side validation can be enabled through the browser's [Constraint Validation API](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) for many form controls. You can enable it using props such as `required`, `pattern`, `minlength`, and `maxlength`. As the user interacts with the form control, the `invalid` attribute will reflect its validity based on its current value and the constraints that have been defined.