Home > Mobile >  Organizing React Component Props in TypeScript
Organizing React Component Props in TypeScript

Time:06-23

I just started using TypeScript and I'm wondering what the best approach is when defining Component Props. Say I have a component called 'Entry' that looks like this:

interface EntryProps {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

const Entry = ({ id, label, dateAdded, isComplete }: EntryProps) => {
  // return some JSX
};

This seems fine to me, but where I get confused is when multiple components need to know the structure of the Entry interface. Say I have an 'EntriesList' Component that takes in an array of Entries as a prop, and I have a backend call that needs to return an array of Entries. Should I extract the EntryProps interface into its own module, perhaps in a folder called 'models', and then have the Entry Component take in a single prop 'entry' of type 'EntryInterface'? Or is it not a good practice to have the props for the Entry component defined outside of the actual Component file? I suppose I could export the EntryProps from the Entry Component file but then the name 'EntryProps' seems a little misleading.

If anyone has tips on the subject, I'd really appreciate it, thank you.

CodePudding user response:

First, a better way to declare props is like this:

interface EntryProps {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

const Entry: React.FC<EntryProps> = ({ id, label, dateAdded, isComplete }) => {
  // return some JSX
};

This way, any default props like children are included.

I would keep props interfaces separate from API response interfaces, even if they are identical. You could have something like this:

interface Entry {
  id: string;
  label: string;
  dateAdded: Date;
  isComplete: boolean;
}

interface EntryResponse extends Entry {}

interface EntryProps extends Entry {}

At the moment, all of these things may be identical but this approach gives you more flexibility to differentiate later if necessary.

Another good thing to do is move your types into a types.d.ts file. This keeps your code from being too cluttered and .d.ts files are not transpiled, which probably offers some minimal efficiency improvement.

  • Related