Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const Vs function to create component in React Typescript

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

like image 912
Gen Tan Avatar asked Sep 26 '26 01:09

Gen Tan


2 Answers

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>
}
like image 81
theonly1me Avatar answered Sep 28 '26 00:09

theonly1me


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.

like image 43
shahryarab Avatar answered Sep 28 '26 00:09

shahryarab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!