Share State between two specific instances of the same react component React

  javascript, reactjs, state

Before y’all say global state(redux), I’d like to say one thing. I’m mapping through an array I fetched from my API. I receive images and map over them and render my Slider component. Every 2 sliders must share the same state. So, then if i move to the next slide in the first slider, then the second slider must also go to the next slide(but not any other slides). If I move to the next slide in the 5th slider, the 6th must also move to the next slide… so on.

Component where I map over slides:

<div className='image-grid'>
                {screenshots.map((imagesByResolution, resIdx, screenshotResArr) => {
                    return imagesByResolution.map((img, scriptIdx, screenshotScriptsArr) => {
                        return <Slider slides={formattedSlides} />;
                    });
                })}
            </div>

Slider:

import Button from '@material-ui/core/Button';
import MobileStepper from '@material-ui/core/MobileStepper';
import { useTheme } from '@material-ui/core/styles';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import React from 'react';
import SwipeableViews from 'react-swipeable-views';
import { autoPlay } from 'react-swipeable-views-utils';
import { encodeImage } from '../services/images';
import useStyles from '../styles/slider';

const AutoPlaySwipeableViews = autoPlay(SwipeableViews);

export interface ISlide {
    title: string;
    img: ArrayBuffer;
}

interface Props {
    slides: ISlide[];
}

export default function Slider(props: Props) {
    console.log(props);

    const { slides } = props;
    const classes = useStyles();
    const theme = useTheme();

    const [activeSlide, setActiveSlide] = React.useState(0);
    const maxSlides = slides.length;

    const handleNext = () => {
        setActiveSlide((prevActiveStep) => prevActiveStep + 1);
    };

    const handleBack = () => {
        setActiveSlide((prevActiveStep) => prevActiveStep - 1);
    };

    const handleSlideChange = (step: number) => {
        setActiveSlide(step);
    };

    return (
        <div className={classes.root}>
            <div className={classes.header}>
                <h4 className={classes.title}>{slides[activeSlide].title}</h4>
            </div>

            <AutoPlaySwipeableViews
                axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
                index={activeSlide}
                onChangeIndex={handleSlideChange}
                enableMouseEvents
            >
                {slides.map((slide, index) => (
                    <div key={index}>
                        {Math.abs(activeSlide - index) <= 2 ? (
                            <img className={classes.img} src={encodeImage(slide.img, 'image/png')} alt={slide.title} />
                        ) : null}
                    </div>
                ))}
            </AutoPlaySwipeableViews>

            <MobileStepper
                steps={maxSlides}
                position='static'
                variant='text'
                activeStep={activeSlide}
                nextButton={
                    <Button size='small' onClick={handleNext} disabled={activeSlide === maxSlides - 1}>
                        Next
                        {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
                    </Button>
                }
                backButton={
                    <Button size='small' onClick={handleBack} disabled={activeSlide === 0}>
                        {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
                        Back
                    </Button>
                }
            />
        </div>
    );
}

If this is not possible using either some global state management library or plain ol’ react state, what is the other alternative? Thanks in advance!

Source: Ask Javascript Questions

LEAVE A COMMENT