The component below is designed to react to changes in window resize based on the container height.
However, there seems to be an issue where the containerHeight variable increases as the window size decreases, but does not decrease when I make the window size bigger. It remains at its last maximum value. *** What's confusing is that if I remove the "line-height: 1.25rem;" from the code-container class, everything works perfectly!
Some notes:
- I am using debouncing on the resize handler to prevent frequent calculations.
- Flexbox is being used for the code-container and line-numbers classes.
import { useState, useEffect, useRef } from "react";
import styles from "./CodeBlock.module.css";
function debounce(fn, ms) {
let timer;
return (_) => {
clearTimeout(timer);
timer = setTimeout((_) => {
timer = null;
fn.apply(this, arguments);
}, ms);
};
}
const CodeBase = (props) => {
const codeContainerRef = useRef(null);
const [lineCount, setLineCount] = useState(0);
useEffect(() => {
const debouncedHandleResize = debounce(() => {
const lineHeight = 20; // Value based on CSS
const containerHeight = codeContainerRef.current.clientHeight;
console.log(containerHeight);
const calculatedLineCount = Math.floor(containerHeight / lineHeight);
setLineCount(calculatedLineCount);
}, 500);
debouncedHandleResize();
window.addEventListener("resize", debouncedHandleResize);
return () => {
window.removeEventListener("resize", debouncedHandleResize);
};
}, []);
return (
<div className={styles["code-container"]} ref={codeContainerRef}>
<div className={styles["line-numbers"]}>
{Array.from({ length: lineCount }, (_, index) => (
<div key={index + 1} className={styles["line-number"]}>
{index + 1}
</div>
))}
</div>
<div className={styles["code-line"]}>{props.children}</div>
</div>
);
};
export default CodeBase;
And here is the CSS code:
.code-container {
display: flex;
line-height: 1.25rem;
}
.line-numbers {
display: flex;
flex-direction: column;
max-height: 100%; /*Ensure it doesn't exceed container height */
}
.line-number {
color: #777;
font-size: 12px;
}
.code {
overflow-x: auto;
white-space: pre-wrap;
}
.code-line {
padding-left: 8px; /* Add spacing between line numbers and code */
}