JSFiddle - React, Tailwind, and code Playground
by brendanbond
HTML
<link rel="stylesheet" href="https://cdn.form.io/formiojs/formio.full.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.form.io/formiojs/formio.full.min.js"></script>
<div class="container">
<p>
Here, I've added a select component with a custom default value that fetches from local storage and a change event handler that sets to local storage.
</p>
<div id="formio"></div>
</div>
JavaScript
const formDefinition = {
components: [{
type: "select",
label: "Single Select",
key: "fruitSelect",
placeholder: "Select one",
data: {
values: [{
value: 'apple',
label: 'Apple'
},
{
value: 'banana',
label: 'Banana'
},
{
value: 'pear',
label: 'Pear'
},
{
value: 'orange',
label: 'Orange'
}
]
},
dataSrc: "values",
template: "<span>{{ item.label }}</span>",
input: true
}]
}
Formio.createForm(document.getElementById('formio'), formDefinition).then((form) => {
form.on('change', () => {
const component = form.getComponent("fruitSelect");
console.log(component.getValue());
const value = component.getValue();
if (value) {
window.localStorage.setItem('fruit', value);
}
});
const localState = window.localStorage.getItem("fruit");
if (localState) {
console.log("Got local state:", localState);
form.getComponent('fruitSelect').setValue(localState);
}
})