-
Notifications
You must be signed in to change notification settings - Fork 0
Creating a new field
Creating new fields in react-formilicious is rather straight forward. Let's walk through the creation of a simple ToggleField. It works just like a checkbox, just more stylish!
At it's core fields are just React Components. So let's create a component for our ToggleField.
// my-own-fields/ToggleField.js
import * as React from "react";
export default class ToggleField extends React.Component {
}Let's just add the bare minimum for our field to actually be recognizable as a field for Formilicious:
// my-own-fields/ToggleField.js
import * as React from "react";
export default class ToggleField extends React.Component {
static getDefaultValue() {
return false;
}
render() {
return (<div>I am a Formilicious field!</div>);
}
}The getDefaultValue function is called in case our data prop in the form did not have a value for the field.
Let's add it to a form somewhere in our project:
// index.js
import ToggleField from './my-own-fields/ToggleField';
<Form
data={{}}
onSubmit={data => alert(JSON.stringify(data, null, 2))}
elements={[
{
type: ToggleField,
key: "newsletter"
}
]} />Hit "Submit", and we see the following:
Fair enough, that's pretty much what we expected to get.
While showing some static text is really neat, let's start extending this functionality by displaying the current value. We can get the current value of the field by using the value prop.
// index.js
render() {
const { value } = this.props;
return (<div>I am a Formilicious field! My value is <strong>{value.toString()}</strong>.</div>);
}That's some progess. Now it wouldn't be much of a form field if we couldn't change it. Let's add a way to do this.
// index.js
render() {
const { value, onChange } = this.props;
return (<div className="field has-addons">
<p className="control">
<a className={value ? "button is-info" : "button"} onClick={() => onChange(true)} disabled={value}>
<span>🦄 Yes</span>
</a>
</p>
<p className="control">
<a className={value ? "button" : "button is-info"} onClick={() => onChange(false)} disabled={!value}>
<span>No 👹</span>
</a>
</p>
</div>);
}


