I’m working on a React application where I need to display modals with different input field configurations (e.g., text inputs, autocomplete inputs, custom inputs) across various parts of the application. I’m considering creating a single reusable modal component that can handle these different input configurations.
The idea is to have a CustomModal component that accepts an inputs prop as an array of input field objects. Each input field object would have properties like name, label, value, type, options (for autocomplete inputs), and any additional props specific to that input type.
The CustomModal component would then render the appropriate input field based on the type property, allowing me to use the same component for different input configurations.
Here’s an example of what the CustomModal component might look like:
`import React from 'react';
import { Modal, Box, Button } from '@mui/material';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
const CustomModal = ({
open,
onClose,
onSubmit,
title,
inputs,
submitButtonText,
}) => {
const handleSubmit = () => {
const inputValues = inputs.map((input) => ({
name: input.name,
value: input.value,
}));
onSubmit(inputValues);
onClose();
};
const renderInput = (input) => {
switch (input.type) {
case 'text':
return (
<TextField
key={input.name}
name={input.name}
label={input.label}
value={input.value}
onChange={input.onChange}
{...input.props}
/>
);
case 'autocomplete':
return (
<Autocomplete
key={input.name}
options={input.options}
renderInput={(params) => (
<TextField
{...params}
name={input.name}
label={input.label}
value={input.value}
onChange={input.onChange}
{...input.props}
/>
)}
/>
);
default:
return null;
}
};
return (
<Modal open={open} onClose={onClose}>
<Box>
<h2>{title}</h2>
{inputs.map(renderInput)}
<Button variant="contained" onClick={handleSubmit}>
{submitButtonText}
</Button>
</Box>
</Modal>
);
};
export default CustomModal;`
While this approach seems to provide code reusability and a consistent UI across the application, I’m concerned about potential issues like, as the number of input field types and configurations increases, the modal component may become more complex and harder to maintain.
Is it a good idea to have a single reusable modal component for handling different input configurations in React? If not, what would be a better approach