Reputation: 49
I'm trying to map slides inside switch transition and get the error "Error: React.Children.only expected to receive a single React element child."
What I do wrong?
Slider.Body = function SliderBody({ data, children, ...rest }) {
return (
<SwitchTransition mode={"out-in"}>
<TransitionGroup>
{data.map((item) => {
return (
<CSSTransition classNames="fade" key={item.image}>
{item.toString()}
</CSSTransition>
);
})}
</TransitionGroup>
</SwitchTransition>
);
};
Upvotes: 0
Views: 142
Reputation: 489
The problem is that you can't have multiple items in the <TransitionGroup>
component so the solution would be to wrap the map function in an HTML element
.
You could use <React.Fragment>
and wrap your map function in it as well.
Let's look at the example using <React.Fragment>
:
Slider.Body = function SliderBody({ data, children, ...rest }) {
return (
<SwitchTransition mode={"out-in"}>
<TransitionGroup>
<React.Fragment>
{data.map((item, i) => {
return (
<CSSTransition classNames="fade" key={i}>
{item.toString()}
</CSSTransition>
);
})}
</React.Fragment>
</TransitionGroup>
</SwitchTransition>
);
};
You can find more about Fragments here.
Upvotes: 0
Reputation: 828
Wrap the data you are mapping inside a div. So it should look something like this -
Slider.Body = function SliderBody({ data, children, ...rest }) {
return (
<SwitchTransition mode={"out-in"}>
<TransitionGroup>
<div>
{data.map((item) => {
return (
<CSSTransition classNames="fade" key={item.image}>
{item.toString()}
</CSSTransition>
);
})}
</div>
</TransitionGroup>
</SwitchTransition>
);
};
Upvotes: 1