React image slider with dynamic data, first Image coming after clickEvent - javascript

I've built a grid of images coming from an API, and now I am trying to build a slider.
First image to be displayed should be the one clicked in the Grid below the slider , and when clicked next/prev go to the nex/prev img in the array.
How could I get it?
I am trying by setting the initial state of ``ìmgToShow```to the img clicked, but i get nothing in console. The idea would be to get that, and then , i still dont know how, update the state to show the next img in the Array.
album is the array of objects with all the images. Fetched in my Context component
clickedImagecontains the clicked image's URL. I get it from a click event in other component.
This is my component :
import React, { useContext, useState } from "react";
import { AlbumContext } from "../../context/AlbumContext";
import "./carousel.css";
import BtnSlider from "./BtnSlider";
function Carousel() {
const { clickedImage, albums } = useContext(AlbumContext);
const [imgToShow, setImgToShow] = useState(clickedImage);
console.log("imgTOSHOW", imgToShow); // empty in console
console.log("clickedIMG in context", clickedImage); // gives me the URL clicked
const [slideIndex, setSlideIndex] = useState(1);
const nextSlide = () => {
if (slideIndex !== albums.length) {
setSlideIndex(slideIndex + 1);
} else if (slideIndex === albums.length) {
setSlideIndex(1);
}
};
const prevSlide = () => {};
return (
<div className="container-slider">
{albums &&
albums.map((item, index) => {
return (
<div
key={item.id}
className={
slideIndex === index + 1 ? "slide active-anim" : "slide"
}
>
<img src={imgToShow} alt="" />
</div>
);
})}
<BtnSlider moveSlide={nextSlide} direction={"next"} />
<BtnSlider moveSlide={prevSlide} direction={"prev"} />
</div>
);
}
export default Carousel

Related

How to change image src on scroll in reactjs

I want to change the source of image onscroll in reactjs. Like if scrollY is greater than 100 change the image source and if it is greater than 200 change it another source.
i tried to do it but could not. any ideas?
import React, { useEffect, useState, useRef } from 'react';
import './Video.css';
import { useInView } from 'react-intersection-observer';
function Video() {
const videoSrc1 = "https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/6341303c29c5340961dc9ae6_Mco-1-transcode.mp4";
const videoSrc2 = "https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63413ff244f1dc616b7148a0_Mco-transcode.mp4";
const videoSrc3 = "https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63455a67996ba248148c4e31_add-options%20(3)-transcode.mp4";
const img1 = 'https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63455a67996ba248148c4e31_add-options%20(3)-poster-00001.jpg';
const img2 = 'https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63413ff244f1dc616b7148a0_Mco-poster-00001.jpg';
const img3 = 'https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63455a67996ba248148c4e31_add-options%20(3)-poster-00001.jpg';
const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = () => {
const position = window.pageYOffset;
setScrollPosition(position);
};
useEffect(() => {
window.addEventListener('scroll', handleScroll, { passive: true })
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
{
if (scrollPosition>=316){
// this.src={videoSrc2}
}
}
console.log("position;", scrollPosition)
return (
<div className='container'>
<video loop autoPlay muted className='video'>
<source src={videoSrc1} type="video/webm" />
</video>
</div>
)
}
export default Video
You can do a combination of Vanilla JS methods and React methods to achieve this.
Your best best bet is to use the useEffect hook and add an event listener to the Window DOM object based on where on the page the scroll is position.
First you need a function that executes every time the DOM re-renders (scrolling does this)
start by using the useEffect hook
useEffect(() => {}, [])
Next you want a function that executes specifically when you scroll the page
you can add an event handler to the window DOM element
window.addEventListener('scroll',() => {})
Then you want to track the where you are on the page (how far up or how far down)
You can use the window's scrollTop property to return how far up or down you are on the page relative to the top of the page
document.documentElement.scrollTop
Now comes the logic part, you said you want to change the image's src based on how far up or down you've scrolled on the page
This is where, useState, boolean flags and the ternary operator come into play
You can write a useState hook to store the Y position of the scroll, and the useEffect and scroll event listener will keep updating it to the current position
const [scrollPosition, getScrollPositon] = useState(document.documentElement.scrollTop)
finally nest the hook function into the window 'scroll' function and nest that in the useEffect hook
const [scrollPosition, getScrollPositon] = useState(document.documentElement.scrollTop)
useEffect(() => {
window.addEventListener('scroll',() => {
getScrollPositon(document.documentElement.scrollTop);
})
}, [])
AND finally write the logic in your .jsx code to say 'when we are x number of pixel below the top of the screen...change the image source'
const App = () => {
return (
<div className='app'>
<img src={scrollPosition < 1000 ? 'http://imagelinkA.com' : 'http://imagelinkB.com'}>
</div>
);
}
Now you put it all together...
// App.js/jsx
import { useState, useEffect } from 'react';
const App = () => {
// initial scroll positon on page load
const [scrollPosition, getScrollPositon] = useState(document.documentElement.scrollTop)
// hook and event handlers to keep track of and update scroll
useEffect(() => {
window.addEventListener('scroll',() => {
getScrollPositon(document.documentElement.scrollTop);
})
}, [])
// your .jsx code with appropriate boolean flags and use of the ternary operator
return (
<div className='app'>
<img src={scrollPosition < 1000 ? 'http://imagelinkA.com' : 'http://imagelinkB.com'}>
</div>
);
}
Hope I was able to help!
Setting the scroll position will trigger needless rerenders, instead you only want to trigger a rerender when the data source will change.
To select the proper data source, putting the list of data sources in a list is a good way to do this. Then you can properly determine the index of data source to show with something like this:
// Y_OFFSET_DIFFERENCE is the value that determines when the next image should be shown.
const index =
Math.floor(position / Y_OFFSET_DIFFERENCE) % dataSources.length;
You can see how this is properly calculated:
If position = 0 and Y_OFFSET_DIFFERENCE = 100 then 0/100 = 0 and 0 % 2 is 0. 0 is the index of the first element of your list.
If position = 100 and Y_OFFSET_DIFFERENCE = 100 then 100/100 = 1 and 1 % 2 is 1. 1 is the index of the second element in your list.
If position = 150 and Y_OFFSET_DIFFERENCE = 100 then 150/100 = 1.5 and Math.floor(1.5) = 1 and 1 % 2 is 1. 1 is the index of the second element in your list.
If position = 200 and Y_OFFSET_DIFFERENCE = 100 then 200/100 = 2 and 2 % 2 is 0. 0 is the index of the first element in your list.
And it'll continue like this forever.
Here is the full code.
import { useState, useEffect } from "react";
const dataSources = [
"https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63455a67996ba248148c4e31_add-options%20(3)-poster-00001.jpg",
"https://global-uploads.webflow.com/62efc7cb58ad153bfb146988/63413ff244f1dc616b7148a0_Mco-poster-00001.jpg"
];
const DEFAULT_DATA_SOURCE = dataSources[0];
const Y_OFFSET_DIFFERENCE = 100;
export default function App() {
const [dataSource, setDataSource] = useState(DEFAULT_DATA_SOURCE);
useEffect(() => {
const handleScroll = () => {
const position = window.pageYOffset;
const index =
Math.floor(position / Y_OFFSET_DIFFERENCE) % dataSources.length;
const selectedSource = dataSources[index];
if (selectedSource === dataSource) {
return;
}
setDataSource(selectedSource);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [dataSource]);
return (
<div
style={{ height: 2000, backgroundImage: "linear-gradient(blue, green)" }}
>
<div
style={{
position: "sticky",
top: 10,
left: 10,
display: "flex",
justifyContent: "center",
flexDirection: "column",
alignItems: "center"
}}
>
<p style={{ color: "white", textAlign: "center" }}>{dataSource}</p>
<img
src={dataSource}
alt="currently selected source"
width={100}
height={100}
/>
</div>
</div>
);
}
codesandbox demo

how to create a react slider component

I was trying to make a react slider component but for some reasons it doesn't change/update the image on click instead it always displays the same picture. What i'm trying to achieve is when I click the button it updates index and the display image changes according to index position. Even though the index is updating the image is not changing. My attempt at creating the slider component -
import arrow from '../../img/arrow-outlined-crimson.png';
const Slider = ({ images }) => {
let index = 0;
const nextSlide = () => {
index+=1;
if (index > images.length - 1) {
index = 0
}
}
return (
<div className='slider'>
<div ref={sliderRef} className="wrapper">
<img src={images[index]} alt="" className="sliderImg" />
</div>
<img src={arrow} onClick={nextSlide} alt="Arrow" className="sliderIcon iconRight" />
</div>
)
}
export default Slider
Use React State instead of just variables.
Try this:
const [index, setIndex] = React.useState(0)
const nextSlide = () => {
setIndex(index + 1);
if (index > images.length - 1) {
setIndex(1)
}
}

Jquery code is not working in next js . Showing unexpected results but working on react

i am trying to implement an ui requirement. I want to add a active class name to the children div one at a time. 1st it will add the class in first child, and then the class will be removed and to be added in the 2nd child div. And it will infinitly itereate.
Here is my code in next js
$(".softwares_container").each(function () {
(function ($set) {
setInterval(function () {
var $cur = $set
.find(`.${st.active}`)
.removeClass(`${st.active}`);
//store inner html of current item
var $next = $cur.next().length
? $cur.next()
: $set.children().eq(0);
$next.addClass(`${st.active}`);
//store inner element of next item
//set inner html of current item to inner html of next item
var $next_inner = $next.children().eq(0);
setValue({
name: $next_inner.attr('alt'),
description: $next_inner.attr('data-info')
})
// setImage($next_inner.attr('src'))
}, 1000);
})($(this));
});
<div className={`softwares_container ${st.left_container}`}>
<div className={` ${st.img}`} alt="1">
<img src={ae.src} data-info="this is aftereffects" alt="After effects" />
</div>
<div className={st.img} alt="2">
<img src={pr.src} alt="Adobe Premiere pro" />
</div>
<div className={st.img}>
<img src={ps.src} alt="Adobe Photoshop" />
</div>
<div className={st.img}>
<img src={xd.src} alt="Adobe Xd" />
</div>
</div>
But it is not working.it is showing unexpected behaviour. It works fine in react .
Can anyone please give me an alternative solution or tell me how to fix the issue?
Here's the link where you can see the unexpected behaviour.
https://diptnc.ml/about
You can write an effect that sets the classname for elements in an array in a round-robin manner.
// Keep the interval id around so that
// it can be cleared when unsubscribing the effect.
let activeFxId;
/*
Applies active class to an array of HTMLElement in a round-robin manner.
*/
function activeFx(elements) {
activeFxId = setInterval(() => {
const elementsArr = [...elements];
let idx = elementsArr.findIndex((element) => {
return element.classList.contains('active');
});
if (idx === -1) {
idx = 0;
}
elementsArr[idx].classList.remove('active');
elementsArr[(idx + 1) % elementsArr.length].classList.add('active');
}, 2000);
return () => {
clearInterval(activeFxId);
};
}
How you provide this array of elements is left to you. An approach is to store a ref to the parent element containing them and pass that on to the function.
For example,
/* Example component */
import React, {useEffect, useRef} from 'react';
export default () => {
const ref = useRef();
useEffect(() => {
if (ref.current && ref.current.children) {
return activeFx(ref.current.children);
}
});
return (
<div ref={ref}>
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>
);
};

Next JS custom carousel and looping/showing/hiding through items

I have a custom build Next JS carousel that keeps an index of the slide we are on and renders an image or video to the screen. It seems that because it is autoplaying and each slide gets removed and readded every 6 or so seconds the page downloads constant copies of the same video or image when it comes around again. Is this not the correct way of doing this?
So the important part is here
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
It will remove and readd content every slide. Does it waste resrouces constantly downloading them? Is there a better way?
import React from 'react'
//Importing data to use as the slides
import { slides } from './data/slides'
import VideoSlide from './VideoSlide'
import ImageSlide from './ImageSlide'
let slideTimer = null
class Carousel extends React.Component {
constructor(props) {
super(props)
this.state = {
currentImageIndex: 0, //Array index of slide from /data/slides
slideTime: 6, //Timing duration of a slide
}
this.setMyInterval = this.setMyInterval.bind(this)
}
//Runs when this componenet is included in the page
componentDidMount() {
this.setMyInterval()
}
changeSlide(current) {
/*Don't run if we are just clicking the same slide number*/
if (current != this.state.currentImageIndex) {
this.setState({ currentImageIndex: current }) //Change to selected slide1
clearTimeout(slideTimer) //Reset the timer so it's not half way through the countdown when we select another slide
this.setMyInterval() //Rebuild the slide countdown so we are starting at 0 and in sync with our CSS animation
}
}
setMyInterval() {
slideTimer = setInterval(() => {
const lastIndex = slides.length - 1 //Check when we need to loop
const { currentImageIndex } = this.state //Get current slide from state
const shouldResetIndex = currentImageIndex === lastIndex
const index = shouldResetIndex ? 0 : currentImageIndex + 1 //Reset to 0 if we are at the end
this.setState({
currentImageIndex: index, //Set new slide as number obtained from above
})
}, this.state.slideTime * 1000) //Repeat every x seconds
}
componentWillUnmount() {
clearInterval(slideTimer)
}
render() {
return (
<>
<div className="backgroundSlide">
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
<VideoSlide url={slides[0].video} />
{slides[this.state.currentImageIndex].image && (
<ImageSlide
url={slides[this.state.currentImageIndex].image}
timer={this.state.slideTime}
/>
)}
</div>
)}
</>
))}
</div>
</>
)
}
}
export default Carousel
It's not clear from the question that what kind of Carousel logic you have. Usually, we render the whole carousel elements and then let the carousel do its job. As an example consider this CSS only carousel,
https://css-tricks.com/css-only-carousel/
If you use such an approach, you can have all of your slides rendered one time and don't have to worry about the removal/addition of any slides.

React JS Infinite Carousel

I'm building a portfolio app in React JS and one of my pages is an About Me page. I stumbled upon a youtube video that builds an infinite carousel using vanilla JavaScript, and during my initial testing it worked. However, when I navigate away from my 'About Me' page and return, it explodes with a "TypeError: Cannot read property 'style' of null" within my About Me component "stepNext; src/components/about-me/AboutMe.js:34".
import React from "react";
import "./AboutMe.css"
import { Button,
Fade,
Grow,
Typography } from '#material-ui/core'
import { ArrowBackIos, ArrowForwardIos } from "#material-ui/icons";
import { Background, Adventures, Hobbies } from "./about-me-components/index";
export const AboutMe = () => {
const slider = document.querySelector('.slider-about-me')
const carousel = document.querySelector('.carousel-about-me')
let direction = 1
const stepPrevious = () => {
if (direction === 1) {
slider.appendChild(slider.firstElementChild)
}
direction = -1
console.log("Previous", direction)
carousel.style.justifyContent = 'flex-end'
slider.style.transform = 'translate(33%)'
}
const stepNext = () => {
if (direction === -1) {
slider.prepend(slider.lastElementChild)
}
direction = 1
console.log("Next", direction)
carousel.style.justifyContent = 'flex-start'
slider.style.transform = 'translate(-33%)'
}
const sliderAppend = () => {
if (direction === 1) {
slider.appendChild(slider.firstElementChild)
} else if (direction === -1) {
slider.prepend(slider.lastElementChild)
}
slider.style.transition = 'none'
slider.style.transform = 'translate(0)'
setTimeout(() => {slider.style.transition = 'all 0.5s'})
}
return (
<>
<Fade
in={true}
timeout={1500}
>
<div
id='about-me-container'
>
<div className="controls">
<div
className='arrow-span-about-me arrow-left-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepPrevious}
>
<ArrowBackIos
className="arrow-back-about-me"
/>
</Button>
</div>
<div
className='arrow-span-about-me arrow-right-about-me'
>
<Button
className='button-about-me arrow-about-me'
variant='contained'
onClick={stepNext}
>
<ArrowForwardIos
className="arrow-forward-about-me"
/>
</Button>
</div>
</div>
<div
id="about-me-carousel-container"
>
<div
className='carousel-about-me'
>
<div
className='slider-about-me'
onTransitionEnd={sliderAppend}
>
<section className='text-white'><Background /></section>
<section className='text-white'><Adventures /></section>
<section className='text-white'><Hobbies /></section>
</div>
</div>
</div>
</div>
</Fade>
</>
)
}
The only reason I chose this route is because I haven't been able to find a half decent infinite carousel module with easy customization abilities. As much as I would prefer for this to work, I'm open to suggestions and/or solutions. Much appreciated!
I would suggest using useRef instead of document.querySelector
document.querySelector happens outside of that lifecycle, making what it returns unreliable, while refs happen within it. (Though doesn’t get reset because of a lifecycle event like a re-render.) This ensures the object returned by the ref is an accurate representation of the current state of the virtual DOM.
I think this is the reason why you are encountering the said error when you go away and back from the About Page.
Here's an example:
https://codesandbox.io/s/objective-fast-vhc27?file=/src/modalAndButton.jsx:531-648

Categories