Everspace Everspace - 1 month ago 6
Javascript Question

Sometimes an inline style's background-position-x or y attribute is not being set

When I render a component, it's

props
shows that it has the correct values, but the div element it generates is missing either it's
background-position-x
or
background-position-y
.

I do something like the following in a parent class:

//Class ImageSelector is roughly:
onClick() {
this.state.image = randomlySelectImage()
}

render() {
return <ItemIcon image={this.state.image}/>
}


The Icon in question:

class Icon extends React.component
render() {
console.log(this.props.image)

let style = {
width: 48,
height: 48,
background: `url('./img/${this.props.image.sprite}')`,
backgroundPositionX: -this.props.image.x,
backgroundPositionY: -this.props.image.y
}

return <div style={style}/>;
}


When the fudgeup happens, the React dev tools shows that Icon indeed has the appropriate values available
x = 192
and
y = 384
, and even the div's
style
is showing the correct values, while the div element on inspection looks like the following:
url("./img/sprite0.png") -384px
. The
x
value is missing, and I don't understand why.

Answer

While the original problem seems to have no solution (as least as of React v15.3.2), the workaround has ended up being specifying the backgroundPositionX and backgroundPositionY as part of the background property.

class Icon extends React.component
  render() {
    let style = {
      width: 48,
      height: 48,
      background: `url('./img/${this.props.image.sprite}') ${-this.props.image.x}px ${-this.props.image.y}px`
    }

    return <div style={style}/>;
}