2

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;
}
1
  • Can you show the attempt you made with the image? Commented Oct 21, 2018 at 19:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.