I want to adapt this image magnifier code for React Typescript as I do not want to use a library for this. The working Vanilla Javascript Codepen is here. I do not want to copy&paste the CSS into a .css file but to use it with my const styles
. Or alternatively achieve the same result with a styled component.
Apart from the thing that I currently get no reaction what should I use instead of getElementById as manual DOM manipulation is not the best to do I think?
I use the container to center the element. Then we have a magnifyWrapper, which will act as our hover div, so once we hover this div, the magnifying glass will show a bigger version of the image.
Then we add the image and a ghost div in which we will load the large image.
React Typescript Code
import React from 'react';
const styles = {
container: {
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
},
magnifyWrapper: {
position: "relative",
maxHeight: "50vh",
image: {
maxHeight: "inherit",
},
#largeImg: {
background: "url("https://images.unsplash.com/photo-1542856204-00101eb6def4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=975&q=80")",
noRepeat "#fff",
width: "100px",
height: "100px",
boxShadow: "0 5px 10px -2px rgba(0, 0, 0, 0.3)",
pointerEvents: "none",
position: "absolute",
border: "4px solid #efefef",
zIndex: "99",
borderRadius: "100%",
display: "block",
opacity: "0",
transition: "opacity 0.2s",
},
&:hover,
&:active: {
#largeImg: {
opacity: "1"
}
}
}
};
interface Props {
magnified: HTMLElement;
original: HTMLElement;
imgWidth: number;
imgHeight: number;
}
function Magnifier(props: Props) {
document.getElementById("zoom").addEventListener(
"mousemove",
function (e) {
//define all viables, then get entrypoint of mouse by calc the page position minus the
//offset on the element
let original = document.getElementById("main-img"),
magnified = document.getElementById("large-img"),
style = magnified.style,
x = e.pageX - this.offsetLeft,
y = e.pageY - this.offsetTop,
imgWidth = original.width,
imgHeight = original.height,
xperc = (x / imgWidth) * 100,
yperc = (y / imgHeight) * 100;
// Add some margin for right edge
if (x > 0.01 * imgWidth) {
xperc += 0.15 * xperc;
}
// Add some margin for bottom edge
if (y >= 0.01 * imgHeight) {
yperc += 0.15 * yperc;
}
// Set the background of the magnified image horizontal
style.backgroundPositionX = xperc - 9 + "%";
// Set the background of the magnified image vertical
style.backgroundPositionY = yperc - 9 + "%";
// Move the magnifying glass with the mouse movement.
style.left = x - 50 + "px";
style.top = y - 50 + "px";
},
false
);
return (
<div sx={styles.container} >
<div id="zoom" sx={styles.magnifyWrapper}>
<img
src="https://images.unsplash.com/photo-1542856204-00101eb6def4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=975&q=80" id="main-img"
/>
<div sx={styles.largeImg}></div>
</div>
</div>
);
}
export { Magnifier };