i want to show “favorites” item in my favorites component. but since i can’t pass postList component to favorites component i don’t know how to do it.
basically this is what i get from this coding. but i want to show favorite items in another page/component:
Home.js
import React, { useState, useEffect } from "react";
import { getDocs, collection, deleteDoc, doc } from "firebase/firestore";
import { db, auth } from "../../firebase";
import { Link } from "react-router-dom";
import Sidebar from "../Sidebar/Sidebar";
import "./Home.css";
import PostList from "./PostList";
const Home = ({ isAuth, setIsAuth }) => {
const [postLists, setPostList] = useState([]);
const postsCollectionRef = collection(db, "posts");
const [favorites, setFavorites] = useState(localStorage.getItem("dam"));
useEffect(() => {
const getPosts = async () => {
const data = await getDocs(postsCollectionRef);
setPostList(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getPosts();
}, []);
useEffect(() => {
const localData = localStorage.getItem("dam") ?? [];
setFavorites(localData);
}, [setFavorites]);
const addFavorite = (favorite) => {
setFavorites((prevfavorites) => [...prevfavorites, favorite]);
localStorage.setItem("dam", JSON.stringify(favorites));
};
return (
<div className="containers">
<div className="sidebar">
<Sidebar isAuth={isAuth} setIsAuth={setIsAuth} />
<div className="centered">
<div className="bordered">
<button id="ado">
<Link to="/createpost">+ Add API</Link>
</button>
</div>
<div className="new-container">
{postLists?.map((post) => {
return (
<>
<PostList
post={post}
addFavorite={addFavorite}
key={post.id}
/>
</>
);
})}
</div>
</div>
<div className="another">
<h2>FAVORITE ITEMS</h2>
{postLists
.filter((post) => favorites.includes(post.id))
.map((post) => (
<PostList post={post} addFavorite={addFavorite} key={post.id} />
))}
</div>
</div>
</div>
);
};
export default Home;
PostList.js
import React from "react";
const PostList = ({ post, addFavorite }) => {
const { linkin, title, imageURL, photoURL, name, id } = post;
return (
<>
<div>
<div className="post">
<div className="postimage">
<div className="del"></div>
<div className="images">
<a href={linkin}>
<p className="ss">{title}</p>
<img src={imageURL} id="img-photo" />
</a>
<div className="uploader">
<img src={photoURL} />
<p>by {name}</p>
</div>
{addFavorite && (
<div className="butons">
<button onClick={() => addFavorite(id)} id="favori">
+
</button>
</div>
)}
</div>
</div>
</div>
</div>
</>
);
};
export default PostList;
and a empty Favorites.js component.
Favorites.js
favorites here...