the code below give me the following error: Type '() => void' is not assignable to type 'FC<{}>'. Type 'void' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)
Here is the code:
import React, { FC } from 'react';
const Dashboard: FC = () => {
<div>
</div>
};
export default Dashboard;
I've seen similar code that did not produce this error. Can someone please help? Thanks, Sean
CodePudding user response:
If you use the block
syntax, you need to specify the return keyword. Learn more about arrow-function
Try this way.
Example
import React, { FC } from 'react';
const Dashboard: FC = () => {
return(
<div>
Something...
</div>
)
};
export default Dashboard;
Or
import React, { FC } from 'react';
const Dashboard: FC = () => <div> Something... </div>
export default Dashboard;
CodePudding user response:
You should add return keyword since "FC" requires an html element to be returned.
import React, { FC } from 'react';
const Dashboard: FC = () => {
return (
<div>
</div>
)
};
export default Dashboard;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here is a definition of FC
type:
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;
}
As you probably might have noticed, FC
is an alias for FunctionComponent
which in turn is a function with several static properties: propTypes
, contextTypes
...
This function (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
returns wither ReactElement<any,any>
or null
This is a definition of ReactElement
:
interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
type: T;
props: P;
key: Key | null;
}
Consider ReactElement
as jsx
element.
Hence, FC
expects you to return either null
or jsx
element.
Dashboard
is an arrow function. It means it can return an expression without return
keyword. But under one circumstance - expression should be right after =>
symbol.
Please see arrow function docs. It means that you need to do this:
const Dashboard: FC = () => <div></div>