Search code examples
reactjsreact-final-formfinal-form

Is there any way to get if react final form has touched status outside of form


I use react final form in another component, say dialog div and I want to check was this form changed before close this dialog div (to show a message like 'You have unsaved changes').

Here is an example, I have no idea how to call onChange in a form on final-form changes - in tag it will not work in case I use some custom input and in validate method it looks too dirty.

class Dialog extends Component {
    ...
    onFormChange = () => this.setState({isFormChanged: true})
    close() {
        if (this.isFormChanged){
            this.showDialog()
        } else {
            //close dialog
        }
    }
    render(){
        return <div>
            <MyForm onChange={this.onFormChange} />
        </div>
    }
}

and a form

function MyForm({ saveData, onChange, ...props }) {
    return <div>
        <Form
            onSubmit={saveData}}
            render={({
                handleSubmit,
            }) => (
                <form onSubmit={handleSubmit} onChange={() => onChange()}>
                    </form>

Solution

  • Try looking into <FormSpy> helper component and it's onChange prop: https://github.com/final-form/react-final-form#formspyprops