skip to Main Content

I have a homepage that I am trying to import and component into. Using axios I am making the api call on the page.js file in NextJS. I am importing a component; however when I attempt to render that child component it does not display on the screen. I can console.log the data and I can put the data in <pre></pre> tags and it works just find. Below are my page.js file and the component.

Page.JS

 import React from 'react';
    import axios from 'axios';
    import BlogCard from '@/components/BlogCard';

const fecthBlogs = async () => {
  const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API}/blogs`);
  return data;
};

const Home = async () => {
  const blogs = await fecthBlogs();

  return (
    <div className='container'>
      {blogs.map(blog => {
        <BlogCard blog={blog} />;
      })}
    </div>
  );
};

export default Home;

Here is the child component. BlogCard.js

'use client';
import React, { Fragment } from 'react';

const BlogCard = ({ blog }) => {
  return (
    <Fragment>
      <h3>BLOGS</h3>{' '}
      <div className='col-6'>
        <h3>BLOGS</h3>
        <div className='p-3 card'>
          <img
            src={`${process.env.API}/uploads/${blog.image}`}
            alt={blog.title}
            style={{ height: '200px', objectFit: 'cover' }}
            className='card-image-top shadow'
          />
        </div>
      </div>
    </Fragment>
  );
};

export default BlogCard;

2

Answers


  1. In the Home component, you didn’t return BlogCard component in the map method, you just had the curly brackets there. Curly brackets do not return anything.

    To return your BlogCard component inside the map, you can change the render part to:

    return (
      <div className='container'>
        {blogs.map(blog => <BlogCard blog={blog} /> )}
      </div>
    );
    

    or

    return (
      <div className='container'>
        {blogs.map(blog => (
          <BlogCard blog={blog} />
        ))}
      </div>
    );
    

    Additional note: You should probably include the extension of the image (.png, .webp, etc.) in the BlogCard component to display it correctly.

    Login or Signup to reply.
  2. I believe this would have to do with the NEXT_PUBLIC declarative on the image import. The client needs the environment variables to be cleared in this way, the server does not. So the axios call in the page component (server) doesn’t need it, but the Blog component (client) does.

    You can run a console.log() on that environment variable to verify.

    A side note, it is a best practice to use the next/image <Image /> component for images in Next.js. This component is optimized for you, so you don’t have to yourself!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search