Home > Back-end >  const Vs function to create component in React Typescript
const Vs function to create component in React Typescript

Time:11-28

How do I make this component using function instead of const?

const MyComponent: React.FC = () => {
  return <div>My Component</div>;
}

I tried doing this

function MyComponent (): React.FC { 
  return <div>My Component</div>;
}

However, my editor is highlighting the return statement and giving this error:

Type 'Element' is not assignable to type 'FC<{}>'. Type 'ReactElement<any, any>' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.ts

CodePudding user response:

Firstly, I recommend picking up the differences between various ways of declaring functions in JS. i.e you can declare functions as function declarations or function expressions.

Example:

function myFunction(){
    return 'This is a function declaration.'; 
}

const fun1 = function() {
    return 'This is a function expression using a normal function.';
}

const fun = () => {
    return 'This is a function expression with an arrow function.';
}

Now, to answer your question, you cannot use React.FC in a function declaration since in a function declaration when you do the following:

function fun() : React.FC {
//do something
}

Typescript interprets it in a way that you're trying to specify the return type of the fun() function. Instead, what you want to be doing is:

function HomeComponent(): React.ReactNode {
  return <h1>Hello, world!</h1>
}

So that TS understands that this function will return some type of a ReactNode.

When you have props with a function declaration, you'll be doing this:

type Props = {
  message: string;
}

function HomeComponent({ message }): React.ReactNode {
  return <div>{message}</div>
}

CodePudding user response:

Your editor is highlighting it because you are not returning a React Function Component, but a ReactNode.

This should help:

function MyComponent(): React.ReactNode {
  return <div>My Component</div>;
}

CodePudding user response:

In the first one actually, you return a Function component as you see the below code assigned to a const value so you should use (React.fn) for it:

(a const value)  =    ()=>{}

but in the second one, you create a function that returns an Element so you should use (React.ReactElement) for it.

  • Related