Search code examples
javascriptreactjseventsmouseoveronmouseover

Trying to swap image onMouseOver with React


I have 2 image on my database (image and image2). I'm fetching the 2 images from the database but I want the image to change onMouseOver and I don't quite understand how to do to this. All help will be appreciated.

export default class Shop extends Component {
    constructor(props) {
        super(props);
        this.state = {
            products: []
        };
    }

    componentDidMount() {
        this.getProducts();
    }

    getProducts = () => {
        fetch('/users')
         .then(response => response.json())
         .then(response => {
             this.setState({products: response})
         })
    }

    setNewImage = () => {
       
    }

   
     render() {

        const {products} = this.state;
        return (
            <div >

<SideNavBar />
            
            <div className="container">
                   
               {products.map((product) => (
                   <div key={product.image}>
                  <img className="image" src= {product.image} onMouseOver={product.image2} /><br></br>
                 
                 </div>
                 
               ))}
               </div> 


Solution

  • You can simply just manipulate what you get from the products and set in the state with an parameter called 'shownImage', i made the code on sandBox for the example of it working but will leave here too: https://codesandbox.io/s/sad-bartik-lddhg?fontsize=14&hidenavigation=1&theme=dark

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    
    export default class Shop extends Component {
      constructor(props) {
        super(props);
        this.state = {
          products: [
            {
              image: "https://vignette.wikia.nocookie.net/neon-colors/images/0/0c/Neon_red.JPG/revision/latest/window-crop/width/200/x-offset/0/y-offset/0/window-width/217/window-height/217?cb=20130529004401",
              image2: "https://www.tarkett.az/image/cache/catalog/SPOR/V35/C001348-omnisports-r35-ru/royal-blue-200x200.jpg",
              shownImage: "image"
            },
            {
              image: "https://www.tarkett.az/image/cache/catalog/SPOR/V35/C001348-omnisports-r35-ru/royal-blue-200x200.jpg",
              image2: "https://vignette.wikia.nocookie.net/neon-colors/images/0/0c/Neon_red.JPG/revision/latest/window-crop/width/200/x-offset/0/y-offset/0/window-width/217/window-height/217?cb=20130529004401",
              shownImage: "image"
            }
          ]
        };
      }
    
      showDiffrentImage = (imageName, productIndex) => {
        const { products } = this.state;
        products[productIndex].shownImage = imageName;
    
        this.setState({
          products
        });
      };
    
      render() {
        return (
          <div>
            Hello images!
            {this.state.products.map((product, index) => (
              <div>
                <img
                  alt={'ops my img broke'}
                  src={product[product.shownImage]}
                  onMouseOver={() => this.showDiffrentImage("image2", index)}
                  onMouseOut={() => this.showDiffrentImage("image", index)}
                />
              </div>
            ))}
          </div>
        );
      }
    }
    
    ReactDOM.render(<Shop />, document.getElementById("root"));
    

    in your case it would just be this.setState({products: response.map(product => { ...product, shownImage: 'image' })}), or this.setState({products: response.map(product => { image: product.image, image2: product.image2, shownImage: 'image' }})