My text seems to default to hiding particular pieces that don't fit in a div. I would like the whole block to disappear once it no longer fits.
Is there any way to do this?
Here is a sample app of what I currently have:
const App = () => {
return (
<div className='container'>
<p className='text'> If you don't fit you need to be hidden. If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.If you don't fit you need to be hidden.</p>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
.container {
border: 1px solid red;
height: 150px;
width: 150px;
overflow: hidden;
}
<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="app"></div>
TL;DR: working example here.
I don't think there is a css way to do this, but since you're using React, you can take advantage of refs and compute the element size.
Note that you cannot use a standard useRef hook (as far as I know), because changes to these don't trigger a re-render so React won't know when your container overflows.
Instead, you can use a callback ref and store it in the state.
const [textRef, setTextRef] = useState(null);
...
<div ref={(newRef) => setTextRef(newRef)} className="container">
...
</div>
Now that you have a reference to the element, you can compute whether it overflows or not by comparing scrollHeight and offsetHeight properties.
const overflows = textRef.scrollHeight > textRef.offsetHeight;
You have to do this dynamically when the element changes, so place this in an useEffect hook with the textRef as a dependency. Then store the "overflows" property in the state to use it later.
const [overflows, setOverflows] = useState(false);
useEffect(() => {
if (textRef) {
const overflows = textRef.scrollHeight > textRef.offsetHeight;
setOverflows(overflows);
}
}, [textRef]);
Now that you know whether an element overflows and you have that info in the state, you can simply conditionally render the element.
<div ref={(newRef) => setTextRef(newRef)} className="container">
{!overflows && <p className="text">If you don't fit you need to be hidden...</p>}
</div>
Check out this working example where you can see that one element is shown because it has less text and fits, whereas the other is hidden because it overflows.