Add React Reform to your application via
npm install react-reform
Use the createTheme
method and define how your form body and each field should be rendered
import {createTheme} from 'react-reform'
const defautTheme = createTheme({
renderForm: (FormContainer, children, {directProps, isValid}) => (
<FormContainer
style={{background: isValid ? 'green' : 'red', ...directProps.style}}
>
<div>{children}</div>
<button>{directProps.buttonLabel || 'Submit'}</button>
</FormContainer>
),
renderField: (Field, {directProps, name, isFocused, validations, id}) => {
const errors = validations
.filter(({isValid}) => isValid === false)
.map(({errorMessage, name}) => <span key={name}>{errorMessage}, </span>)
return (
<div>
<label htmlFor={id}>
{directProps.label || name}
{!isFocused && errors}
</label>
<Field id={id}
style={{background: isFocused ? 'lightgreen' : 'yellow'}}
{...directProps}
/>
</div>
)
})
Let's add a validTag
validation to the default validations like e.g. required
or maxlength
.
import defaultValidations from 'react-reform/opt/validations'
const validations = {
...defaultValidations,
validTag: {
isValid: val => /#\W+/.test(val),
errorMessage: val => `'${val}' is not a valid tag!`
}
}
React Reform uses react's context to propagate what themes and validations you have enabled for your app.
Therefore you need to wrap your root component with the <ReformContext>
Component like so.
import React, {Component} from 'react'
import {render} from 'react-dom'
import {ReformContext} from 'react-reform'
const themes = {default: defaultTheme};
class App extends Component {
render() {
return (
<ReformContext themes={themes} validations={validations}>
<div>
...Your App Code...
</div>
</ReformContext>
)
}
}
render(<App/>, document.getElementById('root'))
Now that the basics are set up, enjoy writing your forms with very little boilerplate!
import React, {Component} from 'react'
import {Form} from 'react-reform'
import {Text, Textarea} from 'react-reform/opt/inputs'
class TagForm extends Component {
handleSubmit = ({tag, description}, e) => {
...
}
render() {
return (
<div>
<h2>Enter your tag information here</h2>
<Form onSubmit={this.handleSubmit}>
<Text name="tag" isRequired isValidTag/>
<Textarea name="description" label="Enter description"/>
</Form>
</div>
)
}
}