Issue
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): JSX.Element => {\\Some code}
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): JSX.Element => {\\Some code}
Am I missing something to allow such a style?
Thanks
Solution
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.
Answered By - Aifos Si Prahs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.