I have a children component (CollectionsBar.jsx) with a state named collection. When a div gets clicked, it updates the state. I want to access the state in the parent's component (Products.jsx). So when the state gets clicked, it changes the span tag.
Children Component:
import React, { useEffect, useState } from "react";
import useFetch from "../../hooks/useFetch";
import "./CollectionsBar.scss";
const CollectionsBar = () => {
//SETTING DATA FOR useFetch
const { data, loading, error } = useFetch(
"/collection-list?populate[0]=collecao&populate=FundoTitulo&populate[1]=collecao.Imagem&populate=collecao.products&populate=collecao.products.img&populate=collecao.products.img2"
);
const minifyData = data?.attributes.collecao.data;
const [collection, setCollection] = useState();
//COLLECTIONS BAR COMPONENT
return (
<div className="sl-c-collections-bar">
<div className="sl-l-bar__flex">
{minifyData?.map((item, index) => {
return (
<div
onClick={() => {
setCollection(index);
}}
key={index}
className="sl-c-flex__box"
>
<img
src={
import.meta.env.VITE_REACT_APP_UPLOADS_URL +
item.attributes.Imagem.data.attributes.url
}
alt="Imagem Produto"
/>
</div>
);
})}
</div>
</div>
);
};
export default CollectionsBar;
Parent Component:
import React, { useEffect } from "react";
import useFetch from "../../hooks/useFetch";
import CollectionsBar from "../../components/CollectionsBar/CollectionsBar";
import "./Products.scss";
const Products = () => {
return (
<div className="sl-c-products">
<div className="sl-l-products__flex">
<span></span>
</div>
<CollectionsBar />
</div>
);
};
export default Products;
I just want to know the best way of doing it...