Reputation: 1
My component is rendered server side (next.js). Embla Carousel does not work with server rendering.
const [viewportRef, embla] = useEmblaCarousel(
{
slidesToScroll: "auto",
axis: "y",
skipSnaps: true,
},
[WheelGesturesPlugin()]
);
useEffect(() => {
if (!embla) return;
embla.reInit({
slidesToScroll: "auto",
axis: "y",
skipSnaps: true,
});
}, [embla]);
return (
<div ref={viewportRef} className={styles.right_block}>
<div className={styles.slider}>
{courses.map((item, index) => {
return <Slide key={index} {...item} />;
})}
</div>
</div>
)
I tried to reinitialize embla using useEffect, but it didn't help. The problem is exactly Embla. is not initialized on the client side. Since if you resave the component, thereby calling rendering on the client, then Embla Carousel works.
Upvotes: 0
Views: 2093
Reputation: 191
This code cant work on the Server-Side.
Hooks cant be used in a server component. Embla itself is a hook in React and meant for "use client" components. It is also interactive and not static therefore it cant be rendered on the server.
Now how can we still use it?
Just create a component "slider.tsx" and make that component a "use client" component.
Create the EmblaSlider as you would normally. All you need to do is accept children.
'use client';
import useEmblaCarousel from 'embla-carousel-react';
import { EmblaOptionsType } from 'embla-carousel';
import { WheelGesturesPlugin } from 'embla-carousel-wheel-gestures';
import { ReactNode } from 'react';
interface Props {
children: ReactNode;
options?: EmblaOptionsType;
}
export default ({ children }: Props) => {
const [emblaRef] = useEmblaCarousel({ dragFree: true, axis: 'x' }, [
WheelGesturesPlugin({ forceWheelAxis: 'y' }),
]);
return (
<div className="min-w-0 overflow-hidden" ref={emblaRef}>
<div className="flex gap-2">{children}</div>
</div>
);
};
now use it as every other component inside of your server component and pass the data like that:
<SliderComponent>
{someArray.map((data) => {
<div>
{data.example}
</div>
})}
</SliderComponent>
That is an Example with Embla-carousel 8.0.0
https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns
might be worth a read!
Upvotes: 3