Home > other >  How to pass an array prop father to child though an interface (React Hooks)
How to pass an array prop father to child though an interface (React Hooks)

Time:02-23

I have a child component (Gallery) that needs an array (posts) from his father (Homepage). I tried through an interface (GalleryProps) but it's not working.

interface IPost {
    id: number;
    title: string;
    author: string;
    content: string;
}

interface GalleryProps {
    posts: (IPost[]) => void;
}

const Gallery: React.FC<GalleryProps> = (props) => {
    return (
        {posts={props.posts}.map(post =>.map(post =>
            <div className="postCard" key={post.id}>
                <Link className="cardLink" to ={ `/detail/${post.id}`}>
                    <div>
                        {post.title}
                    </div>
                    <div>
                        {post.author}
                    </div>
                </Link>
            </div>
        )}
    );
};

const Homepage: React.FC = () => {
    const [posts, setPosts] = useState<IPost[]>([]);
    let navigateNew = useNavigate();

    useEffect(() => {
        getPosts()
            .then(items => {
                setPosts(items)
            })
    }, []);

    return (
        <div className="containerHomepage">
                <Gallery
                    posts={posts}
                />
        </div>
    );
};

export default Homepage;

I think the problem is in GalleryProps. Do I have the array declaration wrong?

CodePudding user response:

If this data you are having in props of Gallery is in the array , you can write it like below

interface IPost {
    id: number;
    title: string;
    author: string;
    content: string;
}


interface GalleryProps {
  posts: IPost[];
}


const Gallery: React.FC<GalleryProps> = ({posts}) => {
  return (
        posts.map(post => {
          return (
            <div className="postCard" key={post.id}>
                <Link className="cardLink" to ={ `/detail/${post.id}`}>
                    <div>
                        {post.title}
                    </div>
                    <div>
                        {post.author}
                    </div>
                </Link>
            </div>          
          )
        })
  );
};
  • Related