I have a swiper.js slider made in react. If I have 8 images in the swiper and then I navigate to the 8th thumbnail and click on the 7th thumb it will slider the thumbnail part up. Is there a way to prevent this behavior from happening?
What I want to do is for it to only auto slide if there are more slides up or down available. For example, if I have 5 thumbnails and slide [2, 3, 4, 5, 6] are visible, if I select slide 6 it would move over and show slide 7 available and if I select slide 2 it would slide over and show slide 1. That is the only movement I want it to do. Is that feature available in the docs?
<div className="mainSliderWrap">
<Swiper
pagination
onSlideChange={swiper => {
setImageSelectedIndex(swiper.activeIndex + 1)
return true
}}
thumbs={{ swiper: thumbsSwiper }}>
{products.images.map((product, index) => (
<SwiperSlide key={product.originalSrc}>
<img
className={classes.mainSliderImg}
ref={el => {
imagesRef.current[index] = el as HTMLImageElement
}}
src={product.originalSrc}
data-zoom={product.originalSrc}
alt={product.title}
height={360}
width={360}
/>
</SwiperSlide>
))}
</Swiper>
</div>
<div
className={[
"productSlider",
ProductSliderOrientation(width) === "horizontal" &&
"horizontalProductSlider"
].join(" ")}>
<div className="swiper-button-next mainProdNext" />
<div className="swiper-button-prev mainProdPrev" />
<Swiper
direction={ProductSliderOrientation(width)}
touchRatio={1}
threshold={10}
slidesPerView={slidesPerView}
spaceBetween={15}
navigation={{
nextEl: ".mainProdNext",
prevEl: ".mainProdPrev"
}}
onSwiper={setThumbsSwiper}
breakpoints={{
0: {
spaceBetween: 10,
slidesOffsetBefore: 20,
slidesOffsetAfter: 20
},
576: {
spaceBetween: 10,
slidesPerView: 5
},
768: {
touchRatio: 0,
slidesPerView: 5
},
992: {
touchRatio: 1,
slidesPerView: 5
},
1200: {
touchRatio: 0,
slidesPerView: 5
}
}}>
{products &&
products.images.map(product => (
<SwiperSlide key={product.originalSrc}>
<ProductImage
image={product}
alt={products.title}
moduleClass={classes.productImagePick}
gatsbyImageClass={classes.productImagePickGatsby}
/>
</SwiperSlide>
))}
</Swiper>
</div>
</div>
</div>
It looks like there is no way to implement thumbnails with this behavior without manipulating data. So idea is when you change a thumbnail you need to reorder data in order to show next/previous thumb.
export default function App() {
const [thumbsSwiper, setThumbsSwiper] = useState(null);
const [data, setData] = useState([
"https://swiperjs.com/demos/images/nature-1.jpg",
"https://swiperjs.com/demos/images/nature-2.jpg",
"https://swiperjs.com/demos/images/nature-3.jpg",
"https://swiperjs.com/demos/images/nature-4.jpg",
"https://swiperjs.com/demos/images/nature-5.jpg",
"https://swiperjs.com/demos/images/nature-6.jpg",
"https://swiperjs.com/demos/images/nature-7.jpg",
"https://swiperjs.com/demos/images/nature-8.jpg",
"https://swiperjs.com/demos/images/nature-9.jpg",
"https://swiperjs.com/demos/images/nature-10.jpg"
]);
return (
<>
<Swiper
style={{
"--swiper-navigation-color": "#fff",
"--swiper-pagination-color": "#fff"
}}
loop={false}
spaceBetween={10}
navigation={true}
thumbs={{ swiper: thumbsSwiper }}
className="mySwiper2"
onSlideChange={(e) => {
if (e.realIndex % 3 === 0) {
// move first element to the end
const newData = [...data];
newData.push(newData.shift());
setData(newData);
e.slideTo(e.realIndex - 1);
}
if (e.realIndex === 0) {
// move last element to the beginning
const newData = [...data];
newData.unshift(newData.pop());
setData(newData);
e.slideTo(e.realIndex + 1);
}
}}
>
{data.map((img) => (
<SwiperSlide key={img}>
<img src={img} />
</SwiperSlide>
))}
</Swiper>
<Swiper
onSwiper={setThumbsSwiper}
loop={false}
loopedSlides={1}
spaceBetween={10}
slidesPerView={4}
freeMode={false}
watchSlidesVisibility={true}
watchSlidesProgress={true}
className="mySwiper"
>
{data.map((img) => (
<SwiperSlide key={img}>
<img src={img} />
</SwiperSlide>
))}
</Swiper>
</>
);
}
Here is a codesandbox
This is a quick example only. I hope it will help you.
Related
When I delete products from my cart, the last product <CartComponent /> which I want to delete doesn't animate. I use framer-motion to this project and next.js/chakra-ui/redux.
I followed the docs on framer motion with animate-presence:
Multiple children AnimatePresence works the same way with multiple
children. Just ensure that each has a unique key and components will
animate in and out as they're added or removed from the tree.
I recorded a video on youtube to show the problem more clearly:
youtube video showing the problem
Here's cart page below:
// some imports up here :D /\
const MotionBox = motion<BoxProps>(Box);
const Cart = () => {
const selectProducts = useSelector(selectAllDataFromStore);
const dispatch = useDispatch();
return (
<>
<PageLayout title='Koszyk' description='Fake Sugar - koszyk'>
<VStack>
{selectProducts.length > 0 ? (
<Box>
<AnimatePresence>
{selectProducts.map((item) => {
return (
<MotionBox
animate={{ opacity: 1 }}
exit={{ opacity: 0, x: -200 }}
key={item.slug}
>
<CartComponent item={item} />
</MotionBox>
);
})}
</AnimatePresence>
<Box pt={4}>
<Center>
<Divider orientation='horizontal' />
</Center>
<Button mt={2} onClick={() => dispatch(clearCart())}>
Wyczyść koszyk
</Button>
</Box>
</Box>
) : (
<MotionBox
initial={{ opacity: 0, y: -400 }}
animate={{ opacity: 1, y: 0, transition: { duration: 2 } }}
zIndex='tooltip'
>
<Flex direction='column' align='center' justify='center'>
<Heading as='h3' fontSize='3xl'>
Twój koszyk jest pusty.
</Heading>
<NextLink href='/' passHref>
<Button colorScheme='gray'>Przeglądaj produkty</Button>
</NextLink>
</Flex>
</MotionBox>
)}
</VStack>
</PageLayout>
</>
);
};
export default Cart;
edit 1: I didnt mention that before I wrap it with ternary operator, it was animating the last component when I delete it. So everything was good!
so it was like
youtube video: before it worked it was like
const Cart = () => {
const selectProducts = useSelector(selectAllDataFromStore);
const dispatch = useDispatch();
return (
<>
<PageLayout title='Koszyk' description='Fake Sugar - koszyk'>
<VStack>
<Box>
<AnimatePresence>
{selectProducts.map((item) => {
return (
<MotionBox
animate={{ opacity: 1 }}
exit={{ opacity: 0, x: -200 }}
key={item.slug}
>
<CartComponent item={item} />
</MotionBox>
);
})}
</AnimatePresence>
</Box>
</VStack>
</PageLayout>
</>
);
};
export default Cart;
hmm sussy!
I want to set up different transition pages to the left and down and right sides of my Main component that have all the components like [this website][1]
when you click Blog its gonna go right and when click work it'll be going left, I fully complete the animation code but I don't know how can I set it.
down :
initial={{opacity: 0 }}
animate={{opacity: 1, y: 0}}
exit={{opacity: 0, y: '-100vh'}}
transition={{ease:"circOut",type:"tween",duration: 0.5}}
right :
initial={{opacity: 0}}
animate={{opacity: 1, x: 0}}
exit={{opacity: 1, x: '100vw'}}
transition={{ease:"circOut",type:"tween",duration: 1}}
my Main component:
const Main = (props) => {
const [click, setClick] = useState(false)
const handleClick = () => setClick(!click)
return (
<MainContainer
initial={{opacity: 1 } : {opacity: 0}}
animate={{opacity: 1, x: 0}}
exit={{opacity: 1, x: '100vw'}}
transition={{ease:"circOut",type:"tween",duration: 1}}
>
<DarkDiv click={click} />
<Container>
<PowerButton />
<LogoComponent theme={click ? 'dark' : 'light' } />
<SocialIcons theme={click ? 'dark' : 'light'} />
<Center click={click}>
<YinYang onClick={() => handleClick()} width={click ? 120 : 200}
height={click ? 120 : 200} fill='currentColor' />
<span>Click Here</span>
</Center>
<Contact href='mailto:9kbabouziane#gmail.com' rel="noreferrer"
target='_blank'>
<motion.h2>
Say hi..
</motion.h2>
</Contact>
<Blog to =''>
<motion.h2
onClick={() => toast("Coming Soon.." , {
duration: 3000,
position: 'top-center',
style: {background : "#FCF6F4",
color: '#000'},
})}
>
Blog
</motion.h2>
</Blog>
<Toaster/>
<Work to='/work' click={click}>
<motion.h2>
Work
</motion.h2>
</Work>
<BottomBar>
<About to='/about' click={click} >
<motion.h2 >
About.
</motion.h2>
</About>
<Skills to='/skills' click={click}>
<motion.h2>
My Skills.
</motion.h2>
</Skills>
</BottomBar>
</Container>
{click ? <Intro click={click} /> : null}
</MainContainer>
)
}
Now when I click all have the same animation, I want to make a condition when I click blog it'll go right and when I click work it'll go left like that website .. how can I make this, please?
[1]: https://react-portfolio-sigma.vercel.app/
I have a scrollview that has as a child an array of video components. It displays on the UI a carousel of videos. I would like the user to be able to click a play button that is above the video and play that video, but the way my logic is set, all the videos play together because the condition to play the video lives in a react useState.
see the code:
const VideosView = (props) => {
const videoClips = props.route.params.data;
const [state, setState] = React.useState(0);
const [play, setPlay] = React.useState(false);
return (
<>
<SafeAreaView pointerEvents='box-none' style={styles.root}>
<Header
goBack={() => props.navigation.goBack()}
title={state === 0 ? 'RYGGRöRLIGHET' : 'STYRKA & BALANS'}
/>
<View style={styles.paragraphsContainer}>
<Text style={styles.title}>
{state === 0 ? 'Ryggrörlighet' : 'Styrka & Balans'}
</Text>
<Text style={styles.paragraph}>
'Utför övningen i ca 5 min för bästa resultat.'
</Text>
<View style={styles.circlesContainer}>
{renderImages.map((_, index) => {
return (
<TouchableOpacity key={index} onPress={() => setState(0)}>
<View
style={[
styles.circles,
{ opacity: index === state ? 1 : 0.5 }
]}
/>
</TouchableOpacity>
);
})}
</View>
</View>
</SafeAreaView>
<View style={styles.scrollViewContainer}>
<ScrollView
bounces={false}
showsHorizontalScrollIndicator={false}
scrollEventThrottle={30}
onScroll={({ nativeEvent }) => {
const slide = Math.ceil(
nativeEvent.contentOffset.x / nativeEvent.layoutMeasurement.width
);
if (slide !== state) {
setState(slide);
}
}}
horizontal>
{videoClips.map((video, index) => (
<View style={{ position: 'relative' }}>
{!play && (
<TouchableOpacity
style={{
position: 'absolute',
backgroundColor: 'rgba(255,255,255,0.5)',
alignSelf: 'center',
top: 130,
width: 160,
height: 160,
borderRadius: 500,
zIndex: 4000
}}
onPress={() => setPlay(true)}></TouchableOpacity>
)}
<Video
shouldPlay={play}
key={index}
source={{
uri: video
}}
resizeMode='cover'
style={{ width: wp('100%'), height: hp('100%') }}
/>
</View>
))}
</ScrollView>
</View>
</>
);
};
I would like the user to click a button and play one video, use the carousel to go to next video, click play and play the next video.
Please, help.
If you change the play state from Boolean to Number you will probably solve your problem. Here is how:
const [videoBeingDisplayedIndex, setVideoBeingDisplayedIndex] = React.useState(5);
const [play, setPlay] = React.useState(5); // If it is equals to the video id the video should play, else it should not
...
<Button onClick={() => setPlay(videoBeingDisplayedIndex)}>
Play Video
</Button>
<VideoCarousel>
{
myVideoList.map((video, index) => {
return (
<Video
content={video}
index={index}
play={play === index} // Check if the current play state is equals to the video unique id
/>
);
})
}
</VideoCarousel>
...
PS.: please, have in mind that this snippet is abstracting the react-native elements and focusing on the problem.
When i change orientation on tablet the slider breaks (shows 1 broken slide). Expected behavior ( 2 slides 50% width in portrait orientation). I try to fix with ref.current.swiper.update(), but it don't work
const ref = useRef()
const handleResize = () => {
ref?.current.swiper.update()
}
useEventListener('resize', handleResize)
<Swiper
loop
watchOverflow
ref={ref}
className="apartment-swiper"
breakpoints={{
768: {
slidesPerView: 'auto',
},
1280: {
slidesPerView: 1,
},
}}
>
{photo?.map((item, index) => (
<SwiperSlide className="swiper-slide" key={index}>
<img className="swiper-slide" src={item.url} alt="slide" />
</SwiperSlide>
))}
</Swiper>
try to add the parameters updateOnWindowResize or observer properties
<Swiper
loop
watchOverflow
observer={'true'}
className="apartment-swiper"
breakpoints={{
768: {
slidesPerView: 'auto',
},
1280: {
slidesPerView: 1,
},
}}
>
{photo?.map((item, index) => (
<SwiperSlide className="swiper-slide" key={index}>
<img className="swiper-slide" src={item.url} alt="slide" />
</SwiperSlide>
))}
</Swiper>
This problem - swiperRef1.current.swiper.autoplay.timeout = 366 by def!:)
To do:
console.log(swiperRef1.current.swiper)
swiperRef1.current.swiper.autoplay.timeout = 3;
console.log(swiperRef1.current.swiper.autoplay.timeout)
I have a tab component in Material-UI and I want to implement a tooltip on it.
My problem is that when I click the tab component, the tooltip is not disappearing. It must disappear after I click on that tab.
Currently, it continues to be visible even after I click on the tab.
How do I rectify that?
<Tabs
className="navbar-routes"
value={value}
style={{ color: 'green'}}
indicatorColor="secondary"
onChange={handleChange}
>
{
tabsData.map(({id,title,description}) => {
return(
<ToolTip description={description}>
<Tab
style={{
minWidth: 10,
fontSize: '80%',
fontWeight: 'bold',
marginLeft: '-4px',
marginRight: 4
}}
key={id}
component={Link}
to={`/${title}`}
label={`${title}`}
/>
</ToolTip>
);
}
)}
</Tabs>
If you look at the document of Material-UI tooltip API
You would find a props named disableHoverListener
bool
default: false
Do not respond to hover events.
Set it as True would turn off the tooltip onMouseOver event trigger.
Update
Or you can simply make it totally under control.
By binding the onClick, onMouseOver, onMouseLeave, open to related component.
import React, { useState } from "react";
import "./styles.css";
import { Tooltip, Tab } from "#material-ui/core";
export default function App() {
const [flg, setFlg] = useState(false);
const [isHover, setIsHover] = useState(false);
return (
<div className="App">
<Tooltip
title={"message"}
aria-label="add"
placement="bottom"
open={!flg && isHover}
>
<Tab
label={`Click: ${!flg ? "enabled" : "disabled"}`}
onClick={() => setFlg(!flg)}
onMouseOver={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
/>
</Tooltip>
</div>
);
}
Try it online:
You can also implement a generic tooltip with a managed state when to open/close the tooltip.
import Tooltip, { TooltipProps } from "#mui/material/Tooltip";
import { useState } from "react";
/**
* MUI Tooltip wrapper with adaption to the move away once focuses left.
*/
export function ManagedTooltip(props: TooltipProps) {
const [open, setOpen] = useState<boolean>(false);
// Wrap Tooltip with div to capture mouse events
return <div style={{ display: 'flex' }}
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
onClick={() => setOpen(false)}
>
{/* Show the original MUI Tooltip with all props. */}
{/* Just override the open attribute to be fully managed, and disable internal listeners */}
<Tooltip {...props} open={open} disableHoverListener disableFocusListener />
</div>;
}
Once it's ready, you can use it anywhere exactly like the original MUI tooltip.
<Tabs
className="navbar-routes"
value={value}
style={{ color: 'green'}}
indicatorColor="secondary"
onChange={handleChange}
>
{
tabsData.map(({id,title,description}) => {
return(
<ManagedTooltip description={description}>
<Tab
style={{
minWidth: 10,
fontSize: '80%',
fontWeight: 'bold',
marginLeft: '-4px',
marginRight: 4
}}
key={id}
component={Link}
to={`/${title}`}
label={`${title}`}
/>
</ManagedTooltip>
);
}
)}
</Tabs>
The way I solved this was by rendering the tooltip conditionally. In your case I suppose you want the tooltip not to render for the tab of the current active route:
function ConditionalTooltip({renderTooltip, children, ...props}) {
return renderTooltip ? <Tooltip {...props}>{children}</Tooltip> : children;
}
function Tabs() {
const location = useLocation();
return (
<Tabs
className="navbar-routes"
value={value}
style={{ color: 'green'}}
indicatorColor="secondary"
onChange={handleChange}
>
{
tabsData.map(({id,title,description}) => {
return(
<ConditionalTooltip
renderTooltip={location.pathname.indexOf(title) === -1} /* only render tooltip on not active urls */
title={description}
>
<Tab
style={{
minWidth: 10,
fontSize: '80%',
fontWeight: 'bold',
marginLeft: '-4px',
marginRight: 4
}}
key={id}
component={Link}
to={`/${title}`}
label={`${title}`}
/>
</ConditionalTooltip>
);
}
)}
</Tabs>
)
}