react-jsonschema-form
react-jsonschema-form copied to clipboard
Get which field changed on the event onChange
Description
when the field value change,I just want to known which field i changed how can i do?
Steps to Reproduce
- when the field value change,I just want to known which field i changed how can i do?
I was able to accomplish this through the creation of a custom SchemaField component which acts as a wrapper to the original SchemaField and intercepts the onChange event of the underlying field. It then forwards the changed field value, along with the field name, to a callback function provided in the formContext of the form. I used the formContext as I couldn't find another way of passing a custom callback down to the custom SchemaField component.
import React from 'react';
import SchemaField from 'react-jsonschema-form/lib/components/fields/SchemaField';
const CustomSchemaField = function (props) {
const customProps = {};
//Only process if we are dealing with a field, not the parent object
if (props.name) {
const formContext = props.registry.formContext;
//Store the original onChange event provided to the SchemaField
//as well as the name of the field
const { onChange, name } = props;
//Provide a new onChange event for the SchemaField
customProps.onChange = function(formData) {
//Call the custom handler provided in the formContext, if it exists,
//with the field name and new value
if (formContext && formContext.onFieldChange &&
typeof formContext.onFieldChange === 'function') {
formContext.onFieldChange(name, formData);
}
//Call the original onChange handler
onChange(formData);
};
}
return (
<SchemaField {...props} {...customProps} />
);
};
The above would be utilized like so:
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
onFieldChange = (name, formData) => {
//Handle individual field change here...
}
render() {
const formContext = {
onFieldChange: this.onFieldChange
};
return <Form ... fields={{ SchemaField: CustomSchemaField }} formContext={formContext} />
}
}
There certainly may be an easier way...but this has worked for me.
This was fixed in 5.x with https://github.com/rjsf-team/react-jsonschema-form/pull/3173