I am trying to add default values to select fields in my form using react-jsonschema-form. The way I am achieving this is by having custom components. When the custom component is loaded it will call the onChange
function with the default data. An example of when I use this is when I have a date field that I want today to be the default value.
If I only have one custom component that sets a default value, it works. However, if I have multiple fields that require default values, it does not work. I have made a small JSFiddle showing this in action. If you don't change anything and press the submit button you can see that only date4 is set.
We kind of got it working by using an effect and adding a timeout before calling onChange
. This JSFiddle shows what we did, but I cannot get it to work on JSFiddle.
My question is, what's the best way to set a default value programmatically using react-jsonschema-form? I'd really prefer not modifying the schema itself programmatically.
Add the default value in the schema.
properties: {
date: { type: "string", format: "date", default:'2020-06-09' },
date2: { type: "string", format: "date" },
date3: { type: "string", format: "date" },
date4: { type: "string", format: "date" },
description: { type: "string" }
}
You will get the default value in custom widget props
const DatePickerDefaultToToday = (props) => {
const onChange = (e) => {
props.onChange(convertDateToString(e.value));
}
onChange({value: new Date(), syntheticEvent: null, show: true, target: null});
return (<input type="date" onChange={onChange} defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}/>)
}
The default value will get in the props. If the default value is not present,ive added to take it today's date
defaultValue={props.value === undefined ? convertDateToString(new Date()) : props.value}
Another way to set the value is you can pass the formData attribute to the Form.
<Form schema={schema} uiSchema={uiSchema} formData={formData} widgets={customWidget} onSubmit={onSubmit}/>
You can pass the data as key-value p2020-06-09air as name defined in the schema
const formData={{date:'2020-06-09'}}