Home > database >  React writing style: lot of repetition when defining component props
React writing style: lot of repetition when defining component props

Time:10-27

I am new to react and tried to follow a CRA template based on typescript

When I define a component I use an interface with the props such as

interface CompProps {
A: string
B: number
}
const Comp = ({A, B} : CompProps)

Here the component have only two props so it seems tidy enough Yet, I have components with many more props and the phase where I repeat the props name while defining the components bothers me and add many lines of codes.

I am suprised that there is no way to define it in something similar to:

interface CompProps {
A: string
B: number
}
const Comp = (CompProps)

Am I missing something to allow such a style?

Thanks

CodePudding user response:

You're just not used to React & TS yet. No, there's no such syntax and there's no need for that. You have to duplicate the property names twice because you may want to leave some of those like:

Component.types.ts

export interface ComponentProps {
  age?: number;
  name: string;
  surname: string;
}

Component.tsx

import { FC } from 'react';
import { ComponentProps } from './Component.types';

const Component = ({ age = 18, name, email } : ComponentProps) => {
  return null;
};

/*
or

const Component = ({ email } : ComponentProps) => {
  return null;
};

or

const Component = (props : ComponentProps) => {
  return null;
};

or

const Component : FC<ComponentProps> = (props) => {
  return null;
};

const Component : FC<ComponentProps> = ({ surname }) => {
  return null;
};
*/


export default Component;

That's the default TS syntax, same for plain JS TS functions. You cannot make it shorter. It actually makes more sense to destructure these properties from the arguments object manually, it gives you more control.

I recommend you to learn TS in advance, and then learn React TS, as things like this will make more sense for you then.

  • Related