Install

npm

npm install formatic --save

yarn

yarn add formatic

Basic Usage

Basic usage of Formatic is pretty simple. Formatic is just a React component. Pass in the fields as props to render your fields.

import React from 'react';
// Get the Formatic component.
import Formatic from 'formatic';

// Create some fields.
const fields = [
  {
    type: 'single-line-string',
    key: 'firstName',
    label: 'First Name',
  },
  {
    type: 'single-line-string',
    key: 'lastName',
    label: 'Last Name',
  },
];

// Render the form.
React.render(
  <Formatic fields={fields} />,
  document.getElementById('some-element')
);

That example gives us this form:

You can also pass a value for the fields.

import React from 'react';
// Get the Formatic component.
import Formatic from 'formatic';

// Create some fields.
const fields = [
  {
    type: 'single-line-string',
    key: 'firstName',
    label: 'First Name',
  },
  {
    type: 'single-line-string',
    key: 'lastName',
    label: 'Last Name',
  },
];

const value = { firstName: 'Joe', lastName: 'Foo' };

// Render the form with a value.
React.render(
  <Formatic fields={fields} value={value} />,
  document.getElementById('some-element')
);

Used this way, Formatic is a controlled component. So if you try to edit the values in this form, you'll notice you can't.

That's because we're always setting it to a fixed value. We need to use the `onChange` handler to keep the value in sync with the changes, just like with an `input` element.

import React from 'react';
// Get the Formatic component.
import Formatic from 'formatic';

// Create some fields.
const fields = [
  {
    type: 'single-line-string',
    key: 'firstName',
    label: 'First Name',
  },
  {
    type: 'single-line-string',
    key: 'lastName',
    label: 'Last Name',
  },
];

class App extends React.Component {
  state = { firstName: 'Joe', lastName: 'Foo' };

  onChange = newValue => {
    this.setState(newValue);
  };

  render() {
    return (
      <Formatic fields={fields} onChange={this.onChange} value={this.state} />
    );
  }
}

React.render(<App />, document.getElementById('some-element'));

Now above, when we didn't supply a value, we were using Formatic as an uncontrolled component. You can also pass a `defaultValue` and use Formatic as an uncontrolled component.

import React from 'react';
// Get the Formatic component.
import Formatic from 'formatic';

// Create some fields.
const fields = [
  {
    type: 'single-line-string',
    key: 'firstName',
    label: 'First Name',
  },
  {
    type: 'single-line-string',
    key: 'lastName',
    label: 'Last Name',
  },
];

const value = { firstName: 'Joe', lastName: 'Foo' };

// Render the form with a value.
React.render(
  <Formatic defaultValue={value} fields={fields} />,
  document.getElementById('some-element')
);