Ganesh Gujjeti
Ganesh Gujjeti

Reputation: 124

How to change img src onmouseover in ReactJs

** I want to change the image src on mouseover, i have added multiple images dynamically.**

    
        const Servicesdata = [
          {
            ID: "01",
            title: "Power Generation",
            desc:
              " We have rich experience in building thermal, hydro, and combined cycle power plants. We provide customized ready-to-deploy solutions for power plants including total EPC and comprehensive Balance of Plant (BOP) and Flue-gas desulfurization (FGD) solutions.",
            imgsrc: "https://www.tataprojects.com/images/Transmission-Line.jpg",
     imgsrcHover: "https://www.tataprojects.com/images/Sunbstations-min.jpg"
          },
    
          {
            ID: "02",
            title: "Transmission",
            desc:
              "We have successfully commissioned more than 13,000 kms of transmission lines across multiple voltage levels including 800kv HVDC projects",
            imgsrc: "https://www.tataprojects.com/images/Sunbstations-min.jpg",
     imgsrcHover: "https://www.tataprojects.com/images/Sunbstations-min.jpg"
          },
          {
            ID: "03",
            title: "Substations",
            desc:
              "Our optimally designed towers and substation structures allow us to reduce conductor wastage ensuring faster construction and on-time delivery.",
            imgsrc: "https://www.tataprojects.com/images/Tower-Manufactaring-Unit.jpg",
     imgsrcHover: "https://www.tataprojects.com/images/Sunbstations-min.jpg"
          },
    
          {
            ID: "04",
            title: "Tower Manufacturing Unit",
            desc:
              "We have a state-of-the-art manufacturing unit to manufacture transmission line towers and structures. The unit is spread across 40 acres of land.",
            imgsrc: "https://www.tataprojects.com/images/Smart-Grid-min.jpg",
     imgsrcHover: "https://www.tataprojects.com/images/Sunbstations-min.jpg"
          }
        ];
    
        export default Servicesdata;
    
    
    
    
    
        import react from "react";
        import Servicesdata from "../data/Servicesdata";
    
        const Services = () => {
          return (
            <>
              <section className="services">
                <div className="container mt-5">
                  <div className="row">
                    <div className="col-md-12">
                      <h2 className="text-center heading-style-1">Key Areas</h2>
                    </div>
                  </div>
                  {Servicesdata.map((val, index) => {
                    return (
                      <div className="row featurette align-items-center">
                        <div className="col-md-7">
                          <h2 className="featurette-heading">{val.title}</h2>
                          <p className="lead">{val.desc}</p>
                        </div>
                        <div className="col-md-5">
                          <img src={val.imgsrc} className="img-fluid" />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </section>
            </>
          );
        };
    
        export default Services;
    
    
    
    
    
    
    
    
    
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    
    

Upvotes: 0

Views: 86

Answers (2)

Nithish
Nithish

Reputation: 6029

We can make use of onMouseOver & onMouseOut event handlers in order to toggle the images of the current hovering image.

  • We can store the ID of the object in the state when we hover on the image of that particular object
  • And reset it to "" on mouse out
  • In render we can check the ID in the state with the object id, if they are matching then use imgsrcHover else use imgsrc

const Servicesdata = [{ID:"01",title:"Power Generation",desc:" We have rich experience in building thermal, hydro, and combined cycle power plants. We provide customized ready-to-deploy solutions for power plants including total EPC and comprehensive Balance of Plant (BOP) and Flue-gas desulfurization (FGD) solutions.",imgsrc:"https://www.tataprojects.com/images/Transmission-Line.jpg",imgsrcHover:"https://www.tataprojects.com/images/Sunbstations-min.jpg"},{ID:"02",title:"Transmission",desc:"We have successfully commissioned more than 13,000 kms of transmission lines across multiple voltage levels including 800kv HVDC projects",imgsrc:"https://www.tataprojects.com/images/Sunbstations-min.jpg",imgsrcHover:"https://www.tataprojects.com/images/Sunbstations-min.jpg"},{ID:"03",title:"Substations",desc:"Our optimally designed towers and substation structures allow us to reduce conductor wastage ensuring faster construction and on-time delivery.",imgsrc:"https://www.tataprojects.com/images/Tower-Manufactaring-Unit.jpg",imgsrcHover:"https://www.tataprojects.com/images/Sunbstations-min.jpg"},{ID:"04",title:"Tower Manufacturing Unit",desc:"We have a state-of-the-art manufacturing unit to manufacture transmission line towers and structures. The unit is spread across 40 acres of land.",imgsrc:"https://www.tataprojects.com/images/Smart-Grid-min.jpg",imgsrcHover:"https://www.tataprojects.com/images/Sunbstations-min.jpg"}];

const { useState } = React;

const Services = () => {
  //Store the currently hovered object's id in the state
  //Initially it'll be ""
  const [currentHoveredId, setCurrentHoveredId] = useState("");
  
  //On mouse over update the id with the cuurent object's ID
  const onMouseOver = (id) => {
    setCurrentHoveredId(id);
  }
  
  //On moving the cursoe out of the image, then reset it to ""
  const onMouseOut = () => {
    setCurrentHoveredId("");
  }
 
  return ( 
    <section className="services">
      <div className="container mt-5">
        <div className="row">
          <div className="col-md-12">
            <h2 className="text-center heading-style-1">Key Areas</h2>
          </div>
        </div>
        {Servicesdata.map((val, index) => { 
          return (
            <div className="row featurette align-items-center" key={val.ID}>
              <div className="col-md-7">
                <h2 className="featurette-heading">{val.title}</h2>
                <p className="lead">{val.desc}</p>
              </div>
              <div className="col-md-5">
              {/* Toggle the image source based on the result of the id in state and the id of the current object */}
                <img src={currentHoveredId === val.ID ? val.imgsrcHover : val.imgsrc} 
                  className="img-fluid" 
                  onMouseOver={() => {onMouseOver(val.ID)}} 
                  onMouseOut={onMouseOut}/>
              </div>
            </div>
          ); 
        })}
      </div>
    </section>
  );
};

ReactDOM.render(<Services />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

<div id="react"></div>

I have used your code as it is just added the corresponding event handlers and the state as mentioned above.

Upvotes: 1

K K
K K

Reputation: 18099

Make the following modifications in the code:

this.setState({
  servicesData: ServicesData;
})

And call the below function on mouseover,passing the index and the newSrc as parameter:

imgSrcUpdate(index, newSrc) {
  let oldData = this.state.servicesData;
  oldData[index][src] = newSrc;
  this.setState({
    servicesData: oldData
  })
}

Instead of this:

{Servicesdata.map((val, index) => { ...

Use :

{this.state.servicesData.map((val, index) => {....

Upvotes: 0

Related Questions