0

I am working on a feature in a React application that allows users to click an image to set it as their dashboard background. The premise is pretty basic, when the user clicks the wallpaper setting in their menu settings, I perform an ajax request to a JSON file to grab the url of the images sitting on the server.

if(this.state.wallpaper === true) {
      let x = 0;
      var defaultWallpapers = this.state.content.map(image => {
        x++;
        // Need to set image as a background so we can overlay
        // things on top of the image.
        var backgroundStyle = {
          backgroundImage: 'url(' + image.url + ')',
          backgroundSize: 'cover'
        }
        return (
          <div key={x} className="col-xs-4">
            <div className="imageBox" style={backgroundStyle}></div>
          </div>
        );
      })
    }
    else {
      var defaultWallpapers = null;
    }

Everything works great, except for one thing I would like to do. I want to set an overlay on whatever image the user selects. I got a version of that working, but like I assumed would happen, the overlay was applied to every image.

Does anyone have any pointers on how I would specifically target ONLY the image that is clicked by the user?

1 Answer 1

1

So one thing you can do is store the currently selected image's URL in your component's state. If you do this whenever the user selects an image, you can then conditionally add a style based on whether the image is also the user's currently selected image.

var backgroundStyle = {
  backgroundImage: 'url(' + image.url + ')',
  backgroundSize: 'cover'
};

if (this.state.currentImage === image.url) {
  backgroundStyle['opacity'] = 0.5;
}

return (
  <div key={x} className="col-xs-4">
    <div
      className="imageBox"
      style={backgroundStyle}
      onClick={() => this.setWallpaper(image)}
    ></div>
  </div>
);

(Obviously you can do whatever you want to add the overlay. Just for simplicity's sake I chose to make the image slightly transparent to indicate it's already selected.)

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

1 Comment

This is legit. I am going to mark this as correct as it's also given me your solution, and another idea as well. Thanks a lot.

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.