I am using next, typescript, and swiper. I want the current slide/section to be highlighted in the navbar. I was able to achieve this using vanilla javascript https://codepen.io/ms9ntQfa/pen/eYrxLxV but have no idea how to do this in tsx.
This is my code so far
import type { NextPage } from 'next'
import { Swiper, SwiperSlide } from "swiper/react";
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import "swiper/css";
import { Mousewheel } from "swiper";
const Home: NextPage = () => {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<div className={styles.card}>
<div className={styles.header}>
<div className={styles.navbar}>
<h2>Logo</h2>
<ul className={styles.items}>
<li>Home</li>
<li>Foo</li>
<li>Bar</li>
</ul>
</div>
</div>
<Swiper
direction={"horizontal"}
slidesPerView={1}
mousewheel={true}
modules={[Mousewheel]}
className={styles.swiper}
>
<SwiperSlide id="home">Home</SwiperSlide>
<SwiperSlide id="foo">Foo</SwiperSlide>
<SwiperSlide id="bar">Bar</SwiperSlide>
</Swiper>
</div>
</main>
</>
)
}
export default Home
CodePudding user response:
I think there is something you can change with your code:
- Extract the Navbar
<li>
to an array of string then map it out - Create a state to track the active index
- Use
onActiveIndexChange
event ofswiperjs
to get current active slide
I also create a code sandbox, you can see it here
Here is the code snippet:
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import { Swiper, SwiperSlide, useSwiper } from 'swiper/react';
import 'swiper/css';
import React from 'react';
import { Mousewheel } from 'swiper';
const NAV = ['Home', 'Foo', 'Bar'];
export default function Home() {
const [activeIndex, setActiveIndex] = React.useState(0);
const swiper = useSwiper();
return (
<>
<Head>
<title>Create Next App</title>
</Head>
<main>
<div>
<div>
<div>
<h2>Logo</h2>
<ul>
{NAV.map((item, index) => (
<li
key={index}
style={{
color: index === activeIndex ? 'crimson' : 'black',
}}
>
{item}
</li>
))}
</ul>
</div>
</div>
<p>This is horizontal scroll</p>
<Swiper
direction={'horizontal'}
slidesPerView={1}
mousewheel={true}
modules={[Mousewheel]}
style={{
background: 'gold',
}}
onActiveIndexChange={(swiper) => {
setActiveIndex(swiper.activeIndex);
}}
>
<SwiperSlide id="home">Home</SwiperSlide>
<SwiperSlide id="foo">Foo</SwiperSlide>
<SwiperSlide id="bar">Bar</SwiperSlide>
</Swiper>
</div>
</main>
</>
);
}