Search code examples
if-statementnext.jsjsx

How would I add a conditional render to my image in Next-js?


I only want the image to display for each post on the page if there is a valid image. If there is no image,

if(!post.image_url)

I want to display a heading 'image unavailable' However I am unsure how I would go about this, as I cannot write this within the JSX as far as I know.

here is my code, any help would be appreciated

import Link from "next/link";
import Image from "next/image";
import { revalidatePath } from "next/cache";

export default async function Page({ params }) {
 
 console.log(params.posts);
  
const posts = (await sql`SELECT * FROM posts01`).rows;

  return (
    <div className="p-4">
      <h1 className="text-3xl font-bold mb-4"> Posts</h1>
      <div key={posts.post_id}>
        {posts.map((post) => (
          <div key={post.id}>
            <Link
              href={`/allPosts/${post.post_id}`}
              className="text-xl font-bold hover:underline mb-2"
            >
              <h3 className="text-xl font-bold hover:underline mb-2">
                {post.title}
              </h3>
              <h5 className="text-lg">{post.content}</h5>
            </Link>
            {/* // if there is no image, display image unavailable  text */}
            {<Image src={post.image_url} alt="" width={300} height={300} />}
          </div>
        ))}
      </div>
    </div>
  );
}   

Solution

  • You can use an inline if/else in the JSX like so:

    return (
        <div className="p-4">
            <h1 className="text-3xl font-bold mb-4"> Posts</h1>
            <div key={posts.post_id}>
                {posts.map((post) => (
                    <div key={post.id}>
                        <Link
                        href={`/allPosts/${post.post_id}`}
                        className="text-xl font-bold hover:underline mb-2"
                        >
                            <h3 className="text-xl font-bold hover:underline mb-2">
                                {post.title}
                            </h3>
                            <h5 className="text-lg">{post.content}</h5>
                        </Link>
                        {
                            (post.image_url)
                                ? <Image src={post.image_url} alt="" width={300} height={300} />
                                : <p>Sorry the image is unavailable</p>
                        }
                    </div>
                ))}
            </div>
        </div>
    );