I have a component that gets a dynamic text. I am showing ellipsis when the text overflows the width of div. Now, I am showing a show more
and when user clicks on it, I am showing the entire text and show show less
link.
import React from "react";
import "./styles.css";
export default function App(props) {
const [showMore, setShowMore] = React.useState(true);
const onClick = () => {
setShowMore(!showMore);
}
return (
<>
<div className={showMore ? '' : "container"}>{props.text}</div>
<span className="link" onClick={onClick}>{showMore ? 'show less' : 'show more'}</span>
</>
);
}
.container {
overflow-x: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: block !important;
width: 250px;
background-color: #eaeaea;
}
The code above shows show more
link even if the text doesn't overflow.
But I want to show show more
link only when text overflows. How can I achieve that?
EDIT
From crays' comment I found this stackoverflow anwser
Now, I tried using a ref to access the styles as following
import React from "react";
import "./styles.css";
export default function App(props) {
const [showMore, setShowMore] = React.useState(false);
const onClick = () => {
setShowMore(!showMore);
};
const checkOverflow = () => {
const el = ref.current;
const curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
const isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
};
const ref = React.createRef();
return (
<>
<div ref={ref} className={showMore ? "container-nowrap" : "container"}>
{props.text}
</div>
{(checkOverflow()) && <span className="link" onClick={onClick}>
{showMore ? "show less" : "show more"}
</span>}
</>
)
}
I also tried using forwardref
export const App = React.forwardRef((props, ref) => {
const [showMore, setShowMore] = React.useState(false);
const onClick = () => {
setShowMore(!showMore);
};
const checkOverflow = () => {
const el = ref.current;
const curOverflow = el.style.overflow;
if (!curOverflow || curOverflow === "visible") el.style.overflow = "hidden";
const isOverflowing =
el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
};
return (
<>
<div ref={ref} className={showMore ? "container-nowrap" : "container"}>
{props.text}
</div>
{checkOverflow() && (
<span className="link" onClick={onClick}>
{showMore ? "show less" : "show more"}
</span>
)}
</>
);
});
But I am getting an error Cannot read property 'style' of null