-
Notifications
You must be signed in to change notification settings - Fork 15
Getting started: build a GraphQL Form in 5 minutes
Charly POLY edited this page Jun 6, 2018
·
17 revisions
-
yarn add react-apollo-formOR npm i react-apollo-form
then, add to your package.json scripts section:
"react-apollo-form": "react-apollo-form fetch-mutations <graphqlEndpoint> <outpurDir>"-
graphqlEndpointshould be the url of your GraphQL API, ex:"http://localhost:3000/graphql" -
outpurDirshould be the path where files will be generated, ex:"./src/core/forms"
Just run npm run react-apollo-form.
You should see 3 steps : "schema download", "mutations types generations", "json schema generation".
If the commands do not finish with "Done.", please check:
- that your GraphQL server is accessible (up and without authentication)
- that your GraphQL server has 'introspection' enabled !
- that the
outputDiris writable
react-apollo-form expose a configure(options) function with the following options:
interface ApolloFormConfigureOptions {
client: ApolloClient<any>;
jsonSchema: JSONSchema6;
theme?: ApolloFormConfigureTheme;
}-
clientis necessary in order to call the mutation when a form submit -
jsonSchemais necessary for extract mutation arguments as form fields -
themeis optional (see "Theming")
TypeScript Tips
For TypeScript users, configure() takes a "type arguments" for mutations names union types.
The script generates 3 files, including a mutations.d.ts that expose a ApolloFormMutationNames type.
Providing ApolloFormMutationNames to configure() will allow nice autocomplete when building a form (see next section)
import * as React from 'react';
import { configure } from 'react-apollo-form';
import { client } from './apollo'; // a file thats export a configured Apollo Client
const jsonSchema = require('./core/apollo-form-json-schema.json');
export const ApplicationForm = configure<ApolloFormMutationNames>({
// tslint:disable-next-line:no-any
client: client as any,
jsonSchema
});We now have a fresh <ApplicationForm> form component.
Here are the available props:
type ApolloFormProps<MutationNamesType> = {
data: any;
config: ApolloFormConfig & { mutation?: { name: MutationNamesType } };
ui?: UiSchema & ApolloFormUi;
title?: string;
subTitle?: string;
onSave?: (data: object) => void;
onCancel?: () => void;
children?: React.SFC<ApolloRenderProps>;
liveValidate?: boolean;
}| Prop | Description |
|---|---|
data |
initial data to fill the fields |
config |
There is two types of config, see below the table |
ui |
same as react-jsonschema-form, see below the table |
title |
Form title (string) |
subtitle |
Form subtitle (string) |
onSave |
callback after save ((data: object) => void) |
onCancel |
callback on cancel action (() => void) |
liveValidate |
should the form run validation on user actions or on submit ? (boolean, default: false) |