I am trying to add TypeScript in a React app.
Versions:
"react": "16.9.0",
"typescript": "3.5.3",
I have an array like
import aLogo from '../images/a.svg';
import bLogo from '../images/b.svg';
const websites = [
{
name: 'A',
src: aLogo,
url: 'https://a.com',
},
{
name: 'B',
src: bLogo,
url: 'https://b.com',
},
];
I am passing it to a component through props.
interface Website {
name: string;
src: string;
url: string;
}
interface Props {
websites: Website[];
}
const SocialList: React.FC<Props> = (props: Props) => {
const { websites } = props;
return websites.map((website) => {
const { name, src, url } = website;
return (
<a key={name} href={url}>
<img src={src} />
</a>
);
});
};
But it gives me error
TypeScript error in /SocialList.tsx(16,7):
Type '(props: Props) => Element[]' is not assignable to type 'FunctionComponent<Props>'.
Type 'Element[]' is missing the following properties from type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>': type, props, key TS2322
14 | }
15 |
> 16 | const SocialList: React.FC<Props> = (props: Props) => {
| ^
I read the answers in how do you declare an array of objects inside typescript?, but still cannot figure out how to fix it.
React components cannot render (or return for functional components) as arrays, which is what you have currently. You can update your code to return the a
tags within a React.Fragment
, which is basically what you're after but is allowed.
Example:
const SocialList: React.FC<Props> = (props: Props) => {
const { websites } = props;
const websiteElements = websites.map((website) => {
const { name, src, url } = website;
return (
<a key={name} href={url}>
<img src={src} />
</a>
);
});
return (
<React.Fragment>
{ websiteElements }
</React.Fragment>
)
};
Note also that you can use the syntax
<>
{ websiteElements }
</>
instead of <React.Fragment>
if you prefer.
The error is about returning an array of JSX elements which is not a valid return type from a component.
You must return a single node, all you have to do is wrap it inside a fragment <></>
or a <div></div>
etc...
Also you don't need to type props
parameter again
const SocialList: React.FC<Props> = ({ websites }) => (
<>
{websites.map(({ name, src, url }) => (
<a key={name} href={url}>
<img src={src} />
</a>
))}
</>
);
The accepted answer here is not correct as for the reason you get this error. React components can return arrays containing React elements as of React v16. You don't have to return a Fragment.
This is an issue with the react types package, and more specifically an issue with TS itself.
source 1 source 2
As a workaround, you can either suppress this error message, since it is erroneous in itself, or, indeed, return a Fragment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With