Joel Katusiime
Joel Katusiime

Reputation: 23

ReactJs: Display a list of images from an array of urls

So, its my first week doing Javascript and am trying to create a board game in ReactJs. Am generating the board and its squares using an array and the squares display a text that is held in the array at the corresponding index i.e if the array[0] = 'w', the board looks like this However what am trying to do is to have an image appear on the face of the square instead of the letter.

I have tried array[0] = {imgurl} but no progress. How do i achieve this?

This is my App.js

import React, { Component } from 'react';
import './App.css';
import player from './player.png'

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      board: Array(Math.pow(2,2)).fill(''),
      sqr: {width:'50px',height:'50px'},
      brd: {width:'100px',height:'100px'}
    }
    this.state.board[0]='w'
  }

  render() {
    return (
      <div className="app-container">
        <div style={this.state.brd} className="board" >

        {this.state.board.map((cell) => {
          return <div style={this.state.sqr} className="square">{cell}</div>;
        })}

        </div>

      </div>
    )
  }
}

export default App;

This is my App.css

.board {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  margin-left: 10%;

}

.square {
  box-sizing: border-box;
  border: 2px solid black;
  font-size: 2em;
  display: flex;
  justify-content: center;
  align-items: center;
}

Upvotes: 2

Views: 3058

Answers (1)

moodseller
moodseller

Reputation: 212

I take it you want to mount player.png on a cell like in the picture that has the 'w' letter?

You can use something like:

{this.state.board.map((cell, index) => {
    if (index === 0) {
          return <div
            style={Object.assign({background: `url(${player})`}, this.state.sqr)}
            className="square">
            {cell}
            </div>;
    }
})}

If you want to dynamically mount the images you can export the default styling of a square to the .css file and handle the background image styling directly in the .map loop in a much more comfortable way without having to Object.assign.

Upvotes: 1

Related Questions