In my React app using Material UI, I wrote a code to manage the size of the fields of a contact form. Those fields are elements that can be added or removed depending on a configuration.
The code I wrote works as should be but looks ugly and I need help to make it better
let size = 12;
if (useMediaQuery(theme.breakpoints.up('sm'))) {
const hasTime = fieldsConfig.some(
f => f.name === 'preferredContactHours',
);
const hasContactType = fieldsConfig.some(
f => f.name === 'preferredContactWay',
);
if (name === 'phone' && (!hasTime || !hasContactType)) size = 7;
else if (name === 'preferredContactWay' && hasTime) size = 6;
else if (name === 'preferredContactWay' && !hasTime) size = 5;
else if (name === 'preferredContactHours' && hasContactType) size = 6;
else if (name === 'preferredContactHours' && !hasContactType) size = 5;
}
The size by default is 12 so if any of the conditions are not applicable the field will be full size in the grid.
After the if the hasTime
and hasContactType
are about that those fields are optional so I need to see if they are present or not.
The rest is the sizing and the conditions about it regarding if I have or not the field then is a specific size.
What I need is to have it better and efficient then all that verbose way if that could be possible.