'How to lift state in react
I'm struggling with the tutorial of React on how to lift a state. I have built the following:
After learning how to pass a state to a child, I am now wondering how to do it between children.
Parent:
const PostTemplate = ({ data }) => {
const [isIndex, setIndex] = useState(0);
return (
<>
<Slider
setIndex={isIndex}
{...data}
/>
<Views
setIndex={setIndex}
{...data}
/>
</>
);
};
Child1 (Views):
const Views = ({views, setIndex}) => {
return (
<div>
{views.edges.map(({ node: view }, index) => (
<div
onClick={() => {
setIndex(index);
}}
>
<p>Hello</p>
/>
</div>
))}
</div>
);
};
Child2 (Slider):
const Slider = ({views, isIndex}) => {
return (
<Swiper initialSlide={isIndex}>
{views.edges.map(({ node: view }) => (
<SwiperSlide>Slide</SwiperSlide>
))}
</Swiper>
);
};
I would like to do is pass the index of the click “Views” element to the initialSlide prop of the Slider. Right now, this only returns a rather strange error: undefined is not an object (evaluating 'el.classList').
Any help would be very appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
