Skip to content

Instantly share code, notes, and snippets.

@iamsaksham
Created April 1, 2021 09:18
Show Gist options
  • Select an option

  • Save iamsaksham/757687430132e2c5a0a9a367dc569dd6 to your computer and use it in GitHub Desktop.

Select an option

Save iamsaksham/757687430132e2c5a0a9a367dc569dd6 to your computer and use it in GitHub Desktop.
Return field based on the inputType of the JSON
export const fetchFormField = (
fieldItem,
formValues = {},
apiSuggestions = {},
handleFetchSuggestions,
) => {
switch (fieldItem.inputType) {
case 'autocomplete':
return (
<div className="form-autocomplete">
<Field
name={fieldItem.inputKey}
label={
fieldItem.required ? (
<span>
{fieldItem.inputName} <sup>*</sup>
</span>
) : (
fieldItem.inputName
)
}
defaultValue={formValues[fieldItem.inputKey] || ''}
component={Autocomplete}
disabled={!!fieldItem.disabled}
options={apiSuggestions[fieldItem.inputKey] || []}
getOptionLabel={option => option[fieldItem.resultField]}
getOptionSelected={(option, value) =>
option[fieldItem.resultField] === value[fieldItem.resultField]
}
onInputChange={e => {
if (e) {
handleFetchSuggestions(fieldItem, e.target.value);
}
}}
/>
</div>
);
case 'radiogroup':
return (
<div className="form-radiogroup">
<Field
name={fieldItem.inputKey}
id={fieldItem.inputKey}
label={fieldItem.inputName}
component={RadioGroup}
>
{fieldItem.options.map(item => (
<FormControlLabel
key={item.value}
value={item.value}
control={
<Radio classes={{ checked: 'radio-button-checked' }} />
}
label={item.label}
disabled={!!fieldItem.disabled}
classes={{
root: 'radio-button-root',
label: 'radio-button-label',
}}
/>
))}
</Field>
</div>
);
case 'select':
return (
<div className="form-selectfield">
<Field
name={fieldItem.inputKey}
label={
fieldItem.required ? (
<span>
{fieldItem.inputName} <sup>*</sup>
</span>
) : (
fieldItem.inputName
)
}
component={SelectField}
disabled={!!fieldItem.disabled}
variant="outlined"
>
{fieldItem.options.map(item => (
<MenuItem key={item.value} value={item.value}>
{item.label}
</MenuItem>
))}
</Field>
</div>
);
case 'text':
return (
<div className="form-textfield">
<Field
className="input-field"
name={fieldItem.inputKey}
label={
fieldItem.required ? (
<span>
{fieldItem.inputName} <sup>*</sup>
</span>
) : (
fieldItem.inputName
)
}
component={TextField}
disabled={!!fieldItem.disabled}
variant="outlined"
/>
</div>
);
default:
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment