Swiper Component not working in React and throwing Erros - reactjs

So I am following along with a course by Traversy Media called "React Front To Back 2022", at the 16th section of the course in the 5th and 6th videos, he was using the Swiper component. I was following along step-by-step but at the end, it threw an error, so after a bit of thinking and googling I decided to see the solution of the GitHub repository posted by him of the project, I compared the code, seemed the same, I copied it, still, it threw the errors and didn't render the page.
I couldn't find a fix anywhere(google, documentation, youtube, etc), so hopefully someone can help me here. Thank you in advance for the help.
The Errors:
init-swiper.js:25 Uncaught TypeError: Cannot read properties of undefined (reading 'pagination')
at mountSwiper (init-swiper.js:25:1)
at swiper.js:136:1
at commitHookEffectListMount (react-dom.development.js:23049:1)
at invokeLayoutEffectMountInDEV (react-dom.development.js:25010:1)
at invokeEffectsInDev (react-dom.development.js:27304:1)
at commitDoubleInvokeEffectsInDEV (react-dom.development.js:27280:1)
at flushPassiveEffectsImpl (react-dom.development.js:27007:1)
at flushPassiveEffects (react-dom.development.js:26935:1)
at performSyncWorkOnRoot (react-dom.development.js:26032:1)
at flushSyncCallbacks (react-dom.development.js:12009:1)
react_devtools_backend.js:4026 The above error occurred in the <Swiper> component:
at http://localhost:3000/static/js/bundle.js:131862:66
at Slider (http://localhost:3000/static/js/bundle.js:1549:66)
at main
at div
at Explore
at Routes (http://localhost:3000/static/js/bundle.js:120121:24)
at Router (http://localhost:3000/static/js/bundle.js:120046:30)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:118774:23)
at App
Uncaught TypeError: Cannot read properties of undefined (reading 'pagination')
at mountSwiper (init-swiper.js:25:1)
at swiper.js:136:1
at commitHookEffectListMount (react-dom.development.js:23049:1)
at invokeLayoutEffectMountInDEV (react-dom.development.js:25010:1)
at invokeEffectsInDev (react-dom.development.js:27304:1)
at commitDoubleInvokeEffectsInDEV (react-dom.development.js:27280:1)
at flushPassiveEffectsImpl (react-dom.development.js:27007:1)
at flushPassiveEffects (react-dom.development.js:26935:1)
at performSyncWorkOnRoot (react-dom.development.js:26032:1)
at flushSyncCallbacks (react-dom.development.js:12009:1)
The Code:
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { collection, getDocs, query, orderBy, limit } from 'firebase/firestore'
import { db } from '../firebase.config'
import SwiperCore, { Navigation, Pagination, Scrollbar, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper-bundle.css'
import Spinner from './Spinner'
SwiperCore.use([Navigation, Pagination, Scrollbar, A11y])
function Slider() {
const [loading, setLoading] = useState(true)
const [listings, setListings] = useState(null)
const navigate = useNavigate()
useEffect(() => {
const fetchListings = async () => {
const listingsRef = collection(db, 'listings')
const q = query(listingsRef, orderBy('timestamp', 'desc'), limit(5))
const querySnap = await getDocs(q)
let listings = []
querySnap.forEach((doc) => {
return listings.push({
id: doc.id,
data: doc.data(),
})
})
setListings(listings)
setLoading(false)
}
fetchListings()
}, [])
if (loading) {
return <Spinner />
}
if (listings.length === 0) {
return <></>
}
return (
listings && (
<>
<p className='exploreHeading'>Recommended</p>
<Swiper slidesPerView={1} pagination={{ clickable: true }}>
{listings.map(({ data, id }) => (
<SwiperSlide
key={id}
onClick={() => navigate(`/category/${data.type}/${id}`)}
>
<div
style={{
background: `url(${data.imgUrls[0]}) center no-repeat`,
backgroundSize: 'cover',
}}
className='swiperSlideDiv'
>
<p className='swiperSlideText'>{data.name}</p>
<p className='swiperSlidePrice'>
${data.discountedPrice ?? data.regularPrice}{' '}
{data.type === 'rent' && '/ month'}
</p>
</div>
</SwiperSlide>
))}
</Swiper>
</>
)
)
}
export default Slider
GitHub link to the repo

I'm currently facing same issue while following the course On udemy can't seem to find any difference in my code. The fix was, I updated Swiper to the latest version using npm i swiper#latest then changed my imports to import {Navigation, Pagination, Scrollbar, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/css'
and finally updated my swiper components to <Swiper
slidesPerView={1}
pagination={{ clickable: true }}
modules={[Navigation, Pagination, Scrollbar, A11y]}
navigation
scrollbar={{ draggable: true }}
>
{listing.imgUrls.map((url, index) => (
<SwiperSlide key={index}>
<div
style={{
background: `url(${listing.imgUrls[index]}) center no-repeat`,
backgroundSize: 'cover',
minHeight: '26rem',
}}
className='swiperSlideDiv'
></div>
</SwiperSlide>
))}
</Swiper>

Try switching versions for switcher package.
Checkout the package.json of traversary's repo: https://github.com/bradtraversy/house-marketplace/blob/main/package.json

Its coming due to <react.strictmode> remove it from index.js and it works but I don't know why strict mode causes this error

Related

NextJS Error: Hydration failed because the initial UI does not match what was rendered on the server

I am getting the following errors in my nextjs application:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
In the console:
Warning: Expected server HTML to contain a matching <div> in <div>.
at div
at SendTransaction
at div
at MyApp (webpack-internal:///./pages/_app.tsx:39:11)
at PathnameContextProviderAdapter (webpack-internal:///./node_modules/next/dist/shared/lib/router/adapters.js:62:11)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/dist/client.js:301:63)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/dist/client.js:850:919)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:62:1)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:172:11)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:347:11)
I am doing the tutorial on wagmi found here: https://wagmi.sh/examples/send-transaction
My file structure is as such:
comps/transaction.tsx (This is scaled back to as simple as I could make it and it still throws these errors).
import * as React from 'react';
export function SendTransaction() {
return <h1>TEST!</h1>
}
pages/index.tsx
import type { NextPage } from 'next';
import { ConnectKitButton } from 'connectkit';
const Home: NextPage = () => {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<ConnectKitButton />
</div>
);
};
export default Home;
pages/_app.tsx
import { WagmiConfig, createClient, useAccount, useConnect, useDisconnect } from 'wagmi';
import { mainnet, polygon, optimism, arbitrum } from 'wagmi/chains';
import { ConnectKitProvider, getDefaultClient } from 'connectkit';
import { SendTransaction } from '../comps/transaction';
import React from 'react';
const client = createClient(
getDefaultClient({
appName: 'ConnectKit Next.js demo',
//infuraId: process.env.NEXT_PUBLIC_INFURA_ID,
//alchemyId: process.env.NEXT_PUBLIC_ALCHEMY_ID,
chains: [mainnet, polygon, optimism, arbitrum],
})
);
function MyApp({ Component, pageProps }: AppProps) {
const { isConnected } = useAccount();
if (isConnected) {
return (
<div>
{/* Account content goes here */}
<SendTransaction />
</div>
)
}
return (
<WagmiConfig client={client}>
<ConnectKitProvider>
<Component {...pageProps} />
</ConnectKitProvider>
</WagmiConfig>
);
}
export default MyApp;
In the above, pages/_app.tsx, if i remove:
const { isConnected } = useAccount();
if (isConnected) {
return (
<div>
{/* Account content goes here */}
<SendTransaction />
</div>
)
}
It works just fine. I am new to react and nextjs, and I have been pulling my hair out over this problem for a while now.
I have looked here https://nextjs.org/docs/messages/react-hydration-error
(As well as other stackoverflow articles and other documentation)
And I cannot figure out why this hydration error is occurring, especially since my component is so simple. The warning: Warning: Expected server HTML to contain a matching in . Makes no sense as all of my tags seem to be matching up. I am thinking I need to use useEffect for something but cannot figure out what. Any help is appreciated.
function MyApp({ Component, pageProps }: AppProps) {
const { isConnected } = useAccount();
const loading = (
<div>
<SendTransaction />
</div>
);
return (
<WagmiConfig client={client}>
<ConnectKitProvider>
{isConnected ?(loading) : (<Component {...pageProps} />)}
</ConnectKitProvider>
</WagmiConfig>
);
}

react typescript stitches css prop problem, not work

i'm currently working on a project using stitches with cra but i've stuck to a problem with css props.
here's my code
Texts/index.tsx
import React from 'react';
import { TextStyle } from './textStyle';
const Texts = ({ text, css }: PropsType) => {
console.log(css);
return (
<>
<TextStyle css={{ ...css }} >
<>{text}</>
</TextStyle>
</>
);
};
export default Texts;
and this index.tsx is exported to another components
Container/index.tsx
import { styled, css } from '../../../stitches.config';
// atoms
import Texts from 'src/components/atoms/texts';
const PageContainer = () => {
return (
<Container>
<Contents >
<div>
<Texts
css={{ color: 'red' }}
/>
<Texts
css={{ paddingTop: '20px' }}
/>
</div>
</Contents>
</Container>
);
};
export default PageContainer;
as you can see with the above code, contains css as its child but css is never rendered at all
can anyone help me with this issue?
FYI, console.log(css); returned undefined to me.
Thank you in advance!

SwiperSlide onTouchStart/onClick => trigger slideNext()

I want to include this slideshow: https://swiperjs.com/react/
As I find it not very comfortable to drag for the next slide, I want to add an onClick event to the full Slider so the next slide comes.
How can I trigger a slideNext() in React? I have problems reading the documentation / I do not understand it - and it seems the documentation does not tell how to do this in react.
In jquery it would be something like this :
$('section.slideshow').on( 'click', function() {
swiper.slideNext();
});
Here is my react code :
import React from 'react'
import SwiperCore, { Navigation, Pagination, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper.scss'
import 'swiper/components/navigation/navigation.scss'
import 'swiper/components/pagination/pagination.scss'
SwiperCore.use([Navigation, Pagination, A11y])
function Page(){
return (
<div>
<Swiper
onClick={() => console.log('click')}
onTouchStart={() => slideNext() }
>
<SwiperSlide>slide 1</SwiperSlide>
<SwiperSlide>slide 2</SwiperSlide>
</Swiper>
</div>
);
}
export default Page;
You can opt to use the Navigation API as written in the docs
<Swiper
navigation={{
nextEl: '.next',
}}
>
<SwiperSlide className="next">slide 1</SwiperSlide>
<SwiperSlide className="next">slide 2</SwiperSlide>
<SwiperSlide className="next">slide 3</SwiperSlide>
</Swiper>
CodeSandBox: https://codesandbox.io/s/so-react-swiper-next-slide-2714t?file=/src/App.js
For React Hooks
Define a useState like this:
const [my_swiper, set_my_swiper] = useState({});
Then in your swiper define it like this:
<Swiper
slidesPerView={1}
onInit={(ev) => {
set_my_swiper(ev)
}}>
<SwiperSlide>
<div>
Slide 1
</div>
</SwiperSlide>
<SwiperSlide>
<div>
Slide 2
</div>
</SwiperSlide>
</Swiper>
Notice the onInit method to bind to your variable.
Then you can use my_swiper hook to call next/previous functions like this.
my_swiper.slideNext();
my_swiper.slidePrev();
You can call these anywhere to dynamically control your swiper.
Also you can navigate to any slide
my_swiper.slideTo(number);
I used it as below:
<Swiper
getSwiper={this.updateSwiper}
{...params}
>{/*modules={[Navigation]}*/}
{items}
</Swiper>
by these functions:
updateSwiper(value:any) {
this.setState({
swiper: value
});
}
goNext = () => {
if (this.state.swiper !== null) {
this.state.swiper.slideNext();
}
};

Gatsby/React - fade out section on scroll?

I've been trying to use gatsby-plugin-scroll-reveal which uses Sal.js to animate a hero section on my site. I'm trying to make it so that the text in the hero fades in then fades out as you scroll down the page. Right now, I can only get it to fade in. How can I make that happen with Sal.js or another way?
I also tried a different way by creating a component that uses IntersectionObserver DOM API but I couldn't get that to work really.
Here's the component:
import React from 'react';
import ReactDOM from 'react-dom';
function FadeInSection(props) {
const [isVisible, setVisible] = React.useState(true);
const domRef = React.useRef();
React.useEffect(() => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => setVisible(entry.isIntersecting));
});
observer.observe(domRef.current);
return () => observer.unobserve(domRef.current);
}, []);
return (
<div
className={`fade-in-section ${isVisible ? 'is-visible' : ''}`}
ref={domRef}
>
{props.children}
</div>
);
}
export default FadeInSection
I figured out a solution from this article:
https://markoskon.com/scroll-reveal-animations-with-react-spring/
So, I'm using the react-spring to create reveal animations on scroll and react-visibility-sensor to see if the I want animated element is visible.
// App.js
import React from "react";
import { Spring } from "react-spring/renderprops";
import VisibilitySensor from "react-visibility-sensor";
<VisibilitySensor once>
{({ isVisible }) => (
<Spring delay={100} to={{ opacity: isVisible ? 1 : 0 }}>
{({ opacity }) => <h1 style={{opacity}}>Title</h1>}
</Spring>
)}
</VisibilitySensor>

React-use-gesture not working with Storybook

I have my component and the storybook stories file, it renders with no errors but it is not draggable. I am basing my studies into this example from the react-use-gesture Github. I noticed that if I start a new project with create-react-app and paste this code there it works fine, but using storybook it doesn't work. I also notice that in my code the element looks like <div style="x: 0px; y: 0px;"></div> instead of <div style="transform: none;"></div> (code from the example that works), I've been researching and I couldn't find a solution so I came to ask the help of this awesome community.
Goal: To have a draggable card component story on react storybook, using react-spring and react-use-gesture.
Expected results: To be able to drag the component around.
Actual results: Component is not draggable
Error Messages: none.
Component's code:
import React from 'react'
import { useSpring, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'
export function Card() {
const [props,
set] = useSpring(() => ({ x: 0, y: 0, scale: 1 }))
const bind = useDrag(({ down, movement: [x, y] }) => {
set({ x: down ? x : 0, y: down ? y : 0, scale: down ? 1.2 : 1 })
})
return <animated.div {...bind()} style={props} />
}
export default Card;
Stories code:
import React from 'react'
import { storiesOf } from '#storybook/react'
import Card from './Card'
import './card.css'
const Body = ({ children }: any) => (
<div className="wrapper">
<style
dangerouslySetInnerHTML={{ __html: `body { margin: 0; }` }}
/>
{children}
</div>
)
storiesOf('UI Components | Card', module)
.add("Simple Card", () => (
<Body>
<Card />
</Body>
))
You can check my github repo for this and run npm install and npm run storybook
Here is the folder that contains the code above ^ if you want to check the code only.
I found the solution, the codesandbox is using the latest beta of useSpring.
The versions I had were:
"react-spring": "^8.0.27",
"react-use-gesture": "^6.0.14",
and the solution
"react-spring": "9.0.0-beta.34",
"react-use-gesture": "latest"
Maybe this will be of help for someone else as well.

Resources