javascript – Code to change the size of the fields based on that 2 fields are optional inside a contact form


I think your current code looks pretty reasonable. All the logic you’re typing out is required, and it’s quite readable as-is. There are a few tweaks you can consider, but there could well be different opinions on whether it makes the code more elegant or not.

Array search You initially save into 2 variables whether a couple particular properties exist in the array of objects. You can make that a bit nicer by first mapping to an array of .names, then using .includes instead:

const configNames = fieldsConfig.map(config => config.name);
const hasTime = configNames.includes('preferredContactHours');
const hasContactType = configNames.includes('preferredContactWay');

Abstract into a function Your whole code snippet runs for the purpose of figuring out the size to use. Rather than having this block among whatever else may exist on that level, and rather than conditionally reassigning size in a bunch of places, you might consider a function that calculates the size instead:

const size = getSize();

(This also lets you define size with const, which is great)

Save the comparisons into variables Rather than performing the same test multiple times, you can save them into variables first, it’ll help a bit:

const preferredContactWay = name === 'preferredContactWay';
const preferredContactHours = name === 'preferredContactHours';

Group the conditions that result in the same size (just an option, you may or may not like how it looks):

const getSize = () => {
  if (!useMediaQuery(theme.breakpoints.up('sm'))) {
    return 12;
  }
  const configNames = fieldsConfig.map(config => config.name);
  const hasTime = configNames.includes('preferredContactHours');
  const hasContactType = configNames.includes('preferredContactWay');

  if (name === 'phone' && (!hasTime || !hasContactType)) return 7;

  const preferredContactWay = name === 'preferredContactWay';
  const preferredContactHours = name === 'preferredContactHours';

  if (
    (preferredContactWay && hasTime) ||
    (preferredContactHours && hasContactType)
  ) {
    return 6;
  }
  else if (
    (preferredContactWay && !hasTime) ||
    (preferredContactHours && !hasContactType)
  ) {
    return 5;
  }
  return 12;
}