Reputation: 1056
I am trying to use react-responsive caroussel. When adding my images manually, it works with no problem, but when adding them through photos.map, it doesn't work anymore and I get this error:
Type 'Element[]' is not assignable to type 'string'
Any idea here?
import * as React from 'react';
import { Carousel } from 'react-responsive-carousel';
import "react-responsive-carousel/lib/styles/carousel.min.css"
interface Props {
photos?: string[];
}
const Caroussel = ({
photos = ["test1.png", "test2.png"]
}: Props): JSX.Element => {
return (
<Carousel>
//THIS DOESN'T WORK
{photos.map((image) => (
<div>
<img src={image} />
</div>
))}
//THIS WORKS
<div>
<img src="test.png" />
</div>
<div>
<img src="test2.png" />
</div>
</Carousel>
);
};
export default Caroussel;
Upvotes: 2
Views: 224
Reputation: 33111
You just need to wrap it into Reqct.Fragment:
import * as React from 'react';
import { Carousel } from 'react-responsive-carousel';
import "react-responsive-carousel/lib/styles/carousel.min.css"
interface Props {
photos?: string[];
}
const Caroussel = ({
photos = ["test1.png", "test2.png"]
}: Props): JSX.Element => {
return (
<Carousel>
// Wrap it into React Fragment
<>{photos.map((image) => (
<div>
<img src={image} />
</div>
))}</>
<div>
<img src="test.png" />
</div>
<div>
<img src="test2.png" />
</div>
</Carousel>
);
};
export default Caroussel;
I believe thi is because Carousel expects React.ReactChild[];
type but Array.prototype.map
returns JSX.Element[]
. These types are incompatible.
DOn't know why they did it. AFAIK, children should be typed as React.ReactNode
. Please, correct me if I'm wrong.
React.Fragment does not affect your HTML
Upvotes: 2