Home > Software design >  Most concise way to take props in React
Most concise way to take props in React

Time:12-20

The most concise syntax I know for writing a React component, is the following, which always names every input parameter twice.

export function InputXl({
  placeholder,
  value,
}: {
  placeholder: string;
  value: string;
}): JSX.Element {
  return (
    <Input placeholder={placeholder} value={value} size="xl" />
  );
}

Is there a syntax where I only have to name the parameters once? Something like:

export function InputXl({
  placeholder: string;
  value: string;
}): JSX.Element {
  return (
    <Input placeholder={placeholder} value={value} size="xl" />
  );
}

CodePudding user response:

I find this to be the most concise:

type InputXlProps = {
  value: string;
  placeholder: string;
};

export const InputXl: React.FC<InputXlProps> = (props) => (
  <Input placeholder={props.placeholder} value={props.value} size="xl" />
);

CodePudding user response:

If you using typescript You can define your component props type like this:

type InputXlProps = {
  value: string;
  placeholder: string;
};

export function InputXl(props: InputXlProps): JSX.Element {
  return (
    <Input placeholder={props.placeholder} value={props.value} size="xl" />
  );
}

or:

export function InputXl({ value, placeholder }: InputXlProps): JSX.Element {
  return (
    <Input placeholder={props.placeholder} value={props.value} size="xl" />
  );
}

At the end It's discouraged to use React.Fc and you can see the reasons here:

Remove React.FC from Typescript template

  • Related