Skip to content

Creating a new field

Patrick Sachs edited this page Aug 5, 2018 · 13 revisions

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 object from did not have a value for the field included in it.

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.

Clone this wiki locally