React: How to pass an array as props and render a list of images?

Viewed 7214

I am new to react. I want to loop images list(Json) and show these images on screen. So I want to create a prop with Array. But I don't know how to pass Array as props? Would you help take a look?

var images = [
  "./resources/bgdefault.jpg",
  "./resources/bg1.jpg",
  "./resources/bg2.jpg",
  "./resources/bg3.jpg",
  "./resources/bg4.jpg",
  "./resources/bg5.jpg",
  "./resources/bg6.jpg",
  "./resources/bg7.jpg",
  "./resources/bg8.jpg"
];

type State = {
  index: number;
};

type Props = {
  backgroundDuration: number;
  imagePath: Array<string>;
};

export class BackgroundImage extends React.Component<Props, State> {
  timerID: number;

  constructor(props: Props) {
    super(props);
    this.state = {
      index: -1
    };
    this.timerID=0;
  }

.....

  render() {
    const path:string = images[this.state.index];
    return (
      <div
        style={{
          width: "100%",
          height: "100%",
          backgroundSize: "cover",
          backgroundImage: `url(${path})`
        }}
      ></div>
    );
  }
}

3 Answers

You can pass any javascript variable to a prop. So for example, if you want to loop through an array of URLs and render an img tag for each:

// ImageList.js file

function ImageList (props) {
  const { images } = props

  return <div>{ images.map(imgUrl => <img src={imgUrl} />) }</div>
}

And in the parent component you'd have something like:

// App.js file

import ImageList from './ImageList'

function App () {
  const images = [
    "./resources/bgdefault.jpg",
    "./resources/bg1.jpg",
    "./resources/bg2.jpg",
    "./resources/bg3.jpg",
    "./resources/bg4.jpg",
    "./resources/bg5.jpg",
    "./resources/bg6.jpg",
    "./resources/bg7.jpg",
    "./resources/bg8.jpg"
  ]

  return <ImageList images={images} />
}

This example uses function components, but props and JSX work the same way with class components (just use this.props instead of props).

You can pass any type of JavaScript value as a prop:

<BackgroundImage imagePath={images} backgroundDuration={5000}/>

Your render function then accesses the prop as any other prop:

const path:string = this.props.imagePath[this.state.index];
return (
  <div
    style={{
      width: "100%",
      height: "100%",
      backgroundSize: "cover",
      backgroundImage: `url(${path})`
    }}
  ></div>
);

Related