Search code examples
reactjsreact-jsonschema-forms

How to sync 2 fields in react-jsonschema-form?


I am trying to create JsonSchema-Form component but I ran into a problem. I want inputs to change synchronously. There are 2 fields on the form, one is a "Limit" input and the other is a slider(range)input that can be dragged and change the limit value. In other words I want to change limit value by dragging the slider. But I cannot get them to work in sync.I am not really sure how to proceed with this and how to use the Onchange method to do what I want.

Here is a sample of what I'm trying to create:

Codesandbox Link

import "./styles.css";

export default function App() {
  const uiSchema = {
    limitSlider: { "ui:widget": "range" }
  };

  const schema = {
    required: ["limit", "limitSlider"],
    properties: {
      limit: {
        title: "New Limit",
        type: "integer"
      },
      limitSlider: {
        title: "New Limit Range",
        type: "number",
        minimum: 0,
        maximum: 100
      }
    }
  };

  const onChange = (updatedValues) => {
    console.log("onchange", updatedValues);
  };

  const formData = { limit: 10, limitSlider: 10 };
  return (
    <MuiForm
      uiSchema={uiSchema}
      schema={schema}
      formData={formData}
      onChange={onChange}
    />
  );
}

Solution

  • This isn’t working at the moment because you are calling setValue twice and updating it with the unchanged limit in the second call.

    You can sync up the state of the two components bidirectionally by checking if the current value is equal to the slider value and if not, setting it to the new slider value, and otherwise setting it to the input field value

    const onChange = (updatedValues) => {
      if(value !== updatedValues.formData.limitSlider){
    setValue(updatedValues.formData.limitSlider)
      } else {
      setValue(updatedValues.formData.limit)
      }
    }