After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. This element should zoom into the image when hovered over by the mouse, while maintaining its original dimensions.
I have attempted a few methods:
- Changing the style attribute in the onMouseOver and onMouseOut events like so
import React from "react";
const ImageHoverZoom = ({ imagePath }) => {
return (
<img
src={imagePath}
alt=""
style={{ overflow: "hidden" }}
onMouseOver={(e) => (e.currentTarget.style = { transform: "scale(1.25)", overflow: "hidden" })}
onMouseOut={(e) => (e.currentTarget.style = { transform: "scale(1)", overflow: "hidden" })}
/>
);
};
export default ImageHoverZoom;
- Creating a custom css class and applying that to the img element.
index.css:
.hover-zoom {
overflow: hidden;
}
.hover-zoom img {
transition: all 0.3s ease 0s;
width: 100%;
}
.hover-zoom img:hover {
transform: scale(1.25);
}
imageHoverZoom.jsx:
import React from "react";
const ImageHoverZoom = ({ imagePath }) => {
return (
<img
src={imagePath}
alt=""
className="hover-zoom"
/>
);
};
export default ImageHoverZoom;
- I also experimented with a class component featuring state
import React, { Component } from "react";
class ImageHoverZoom extends Component {
state = {
path: this.props.imagePath,
mouseOver: false,
};
render() {
const { path, mouseOver } = this.state;
return (
<img
className={`img-fluid w-100`}
src={path}
onMouseOver={() => this.setState({ mouseOver: true })}
onMouseOut={() => this.setState({ mouseOver: false })}
style={
mouseOver
? { transform: "scale(1.25)", overflow: "hidden"}
: { transform: "scale(1)", overflow: "hidden"}
}
alt=""
/>
);
}
}
Preferably, I would like to avoid using state due to potential lag caused by asynchronous updates. Any assistance on this matter would be greatly appreciated. Thank you in advance!
EDIT:
Despite trying Rahul's solution below both in my project and a new project, no changes were observed upon hovering over the image. Here are the relevant files:
App.js
import "./App.css";
import ImageHoverZoom from "./common/imageHoverZoom";
function App() {
return <ImageHoverZoom imagePath="http://picsum.photos/400/600" />;
}
export default App;
imageHoverZoom.jsx
import React from "react";
const ImageHoverZoom = ({ imagePath }) => {
return (
<div className="img-wrapper">
<img src={imagePath} alt="" className="hover-zoom" />
</div>
);
};
export default ImageHoverZoom;
index.css
.img-wrapper {
overflow: hidden;
}
.hover-zoom img:hover {
transform: scale(1.25);
}