mardi 10 octobre 2023

How can I add more types easily in the future

Imagine I have this data structure:

const elements = [
    { type: 'text', value: '' },
    { type: 'text', multiple: true, value: ['', ''] },
    { type: 'select', value: '' },
    { type: 'select', multiple: true, value: ['', ''] },
    { type: 'date-range', value: { from: '', to: '' } },
    { type: 'date-range', multiple: true, value: { from: '', to: '' } },
    { type: 'area', value: { lat: '', long: '', rad: '' } },
];

Now, I created a Form using React/Typescript and Formik in order to submit this data to an API endpoint. But I feel that my solution is not scalable and I also had the type some props with any.

As you can see, I need to check for the type of the element but also if it's multiple or not. Making my code a bit hard to follow.

You can see my WIP solution in this codesanbox

The core component is this one:

const Field = ({
  element,
  onChange
}: {
  element: Element;
  onChange: (value: any) => void;
}) => {
  return (
    <Box>
      {element.type === "text" && (
        <Text
          value={element.value as any}
          isMultiple={element.multiple}
          onChange={onChange}
        />
      )}
      {/* Here I will add more types */}
      {element.type !== "text" && (
        <div key={element.id}>{JSON.stringify(element, null, 4)}</div>
      )}
    </Box>
  );
};

Basically, what I want to achieve is a way to have multiple components depending on their type, and how to handle the onChange methods without using 'any' (if that's possible). And a way to add more component types in the future.

Thanks a lot

My WIP solution => https://codesandbox.io/s/xenodochial-mopsa-vgkm2c?file=/src/App.tsx

Aucun commentaire:

Enregistrer un commentaire