0

I'm learning how to use React-TypeScript, and I'm confused with how React.FC and generics work together.

So I have a couple of questions relating to the code below (a functional component returning a list item):

1.) Do you have to pass props as a generic? Or could you simply write

const TodoListItem: React.FC = (props) => {
//code
}

2.) How is it that todo is able to be destructured out of <TodoListItemProps> ?

3.) Why is a return type not defined? Shouldn't it be written as :

const TodoListItem: React.FC<TodoListItemProps> = ({todo}):TodoListItemProps

Full code here:

interface TodoListItemProps {
  todo: {
    text:string
    complete:boolean
  }
}

const TodoListItem: React.FC<TodoListItemProps> = ({todo}) => {
  return(
    <li>
      <label>
        {todo.text}
      </label>
    </li>
  )
}

1 Answer 1

1

You can define your function components two ways.

With only add the types to the function parameters:

const TodoListItem = ({ todo }: TodoListItemProps) => {
  return (
    // ...
  );
};

Or add it as a generic paramter to the FC type:

const TodoListItem: React.FC<TodoListItemProps> = ({ todo }) => {
  return(
    // ...
  );
};

If use use this component both will work just fine, but the FC type adds more to the component. If you inspect the react types you'll see that:

type FC<P = {}> = FunctionComponent<P>;
interface FunctionComponent<P = {}> {
  (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
  propTypes?: WeakValidationMap<P>;
  contextTypes?: ValidationMap<any>;
  defaultProps?: Partial<P>;
  displayName?: string;
}

So from this you can see, that FC (or FunctionComponent) will infer the props for the component (from the generic parameter you provided, and extends it with the children prop), add a propTypes, contextTypes, defaultProps and displayName static field for the compnent. If you don't use these, the first approach is functional, but the FC type will give you more stuff to work with function components.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.