skip to Main Content

Learning about props in react atm, I’m having an issue whereby when I try to pass an image as a prop its won’t display at all, see the screenshot below

enter image description here

import React from "react";
import PropTypes from "prop-types";

import { Link } from "react-router-dom";

const HeroSlider = (props) => {
  const data = props.data;

  return (
    <div className="hero-slider">
      {data.map((item, index) => (
        <HeroSliderItem key={index} item={item} />
      ))}
    </div>
  );
};

HeroSlider.propTypes = {
  data: PropTypes.array.isRequired,
};

const HeroSliderItem = (props) => (
  <div className="hero-slider__item">
    <div className="hero-slider__item__info">
      <div className="hero-slider__item__info__title">
        <span>{props.item.title}</span>
      </div>
      <div className="hero-slider__item__info__description">
        <span>{props.item.description}</span>
      </div>
      <div className="hero-slider__item__info__btn">
        <Link to={props.item.path}>
          <button>Shop Now</button>
        </Link>
      </div>
    </div>
    <div className="hero-slider__item__image">
      <img src={props.item.img} alt="" />
    </div>
  </div>
);

export default HeroSlider;

props data img from my assets folder

2

Answers


  1. You are passing item into HeroSliderItem so you should fix your property path for Img Src:

    
    <img src={props.img} alt="" />
    
    

    I recommend you rename the variable name of the parameter for your component to:

    
    const HeroSliderItem = (item) => (
    
    );
    
    
    

    So you can access the .img property in a more semantic way:

    
    <img src={item.img} alt="" />
    
    
    Login or Signup to reply.
  2. You can store images in variables using images relative path and then use it in your heroSliderData object like bellow.

    const img1 = "../Images/Slider/slide_1.png";
    const img2 = "../Images/Slider/slide_2.png";
    const img3 = "../Images/Slider/slide_3.png";
    
    const heroSliderData = [
      //your objects here
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search