reactjsnext.jsstrapinextjs-image

next/image not working with props as image source


My Home page sends data from my strapi cms to my PostSlider component via props

import React from "react";
import styles from './index.module.scss'
import { AxiosService } from '../utils/axios-service'
import PostSlider from '../components/postSlider/postSlider'

const Home = ({ posts }) => {
  return (
    <div id='contentsWrap' className={styles.dohandsWrap}>
      <PostSlider home={true} posts={posts} />
    </div>
  )
}

export default Home

export async function getStaticProps() {
  const axios = AxiosService.create()
  const res = await axios.get('/archives', {
    params: {
      category: 'news',
      display: true,
      showDoson: true,
      _limit: 5,
      _sort: 'id:DESC'
    }
  })

  return {
    props: {
      posts: res.data,
    },
  }
}

My postSlider component then maps over the data to fill my slider

import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import styles from './postSlider.module.scss'
import Link from 'next/link'
import Image from 'next/image'

export default function PostSlider({ home, posts }) {
  var settings = {
    infinite: posts.length > 2 ? true : false,
    autoplay: false,
    speed: 500,
    autoplaySpeed: 3000,
    slidesToShow: 3,
    slidesToScroll: 1,
  };
  return (
    <section className={`${styles.postSlider} postSlider ${home ? styles.postSliderHome : 'postSliderNotHome'} ${posts.length > 2 ? 'postSliderPadding' : ''}`}>
      <Slider {...settings}>
        {posts.map((post) => {
          const date = new Date(post.displayDate);
          return (
            <Link key={post.id} href={`/news/${post.id}`}>
              <a className={styles.postSliderLink}>
                <article>
                  <Image src={post.images[0]?.url} alt={post.images[0]?.alternativeText} width={376} height={190} layout="fixed" />
                </article>
              </a>
            </Link>
          )
        })}
      </Slider>
    </section>
  );
}

I made sure to include my cdn address in module.exports in next.config.js but I get the following error

Error: Image is missing required "src" property. Make sure you pass "src" in props to the next/image component. Received: {"width":376,"height":190}

error

If I remove the next/image component for the normal img tag, everything works fine.

What am I doing wrong?


Solution

  • Well, it seems that one of your posts has an empty images array?

    Image component is required to have src property and you pass undefined instead.

    You can check if there is at least one image and then render it, like that:

    <article>
      {post.images.length > 0 && (
        <Image src={post.images[0].url} alt={post.images[0].alternativeText} width={376} height={190} layout="fixed" />
      )}
    </article>