Search code examples
javascriptreactjsimage

React Importing Images and Passing them through a prop is not working


I am trying to import images and place them into an array and then pass that array to a prop for a component to display different images. Once I pass the array to the component, items accessed from the array are undefined (and therefore I cannot display them) but console logging the array shows an array of objects being outputted (and not the strings that they should be). Where have I gone wrong?

Here's my code

App.jsx

import { useState, useRef } from "react";
import TransparentMenuBar from "./components/TransparentMenuBar.jsx";
import SlideShow from "./components/SlideShow.jsx";

//Images

import signupScreen from "./assets/SignUpScreen.png";
import racesScreen from "./assets/RacesScreen.png";
import racersScreen from "./assets/RacersScreen.png";

import "./App.css";

const raceImages = [signupScreen, racesScreen, racersScreen];

function App() {
  const homeRef = useRef(null);
  const aboutmeRef = useRef(null);
  const projectsRef = useRef(null);
  const experienceRef = useRef(null);

  return (
    <main>
      <section>
         <SlideShow images={raceImages}></SlideShow>
        </section>
    </main>
  );
}

export default App;

SlideShow.jsx

import { useState } from "react";
import "./SlideShow.css";

export default function SlideShow(images) {
  const [currentImage, setCurrentImage] = useState(images[0]);

  console.log(`Current Image: ${currentImage}`);
  console.log(`Images: ${images}`);
  console.log(`Images[0]: ${images[0]}`);
  return (
    <div>
      <img src={images[0]} />
    </div>
  );
}

Here's the resulting console.log image of log results

I already tried passing the path strings directly inside of the array instead of using imports but that had the same result.


Solution

  • Props provided into a component as object, try instead:

    export default function SlideShow(images) {
    

    get props as object:

    export default function SlideShow({ images }) {