UPDATED QUESTION:
If I type something in the input field before I scroll the expanded
prop gets set to true - correct
If I scroll down - expanded gets set to false - correct
If I type something in the input field now expanded
is still false
- I expect expanded
to be set to true
again.
code:
export default () => {
const [expanded, setExpanded] = useState(true)
let searchInput = React.createRef()
let scrollTopValue = 0;
function handleSearchInput() {
console.log(Boolean(searchInput.current.value.length))
setExpanded(Boolean(searchInput.current.value.length)) // first time true, don't get re triggered
}
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, []);
function handleScroll() {
setExpanded(scrollTopValue > document.documentElement.scrollTop)
scrollTopValue = document.documentElement.scrollTop
}
return (
<header>
{expanded? 'expanded': 'nope'}
<input role="search" ref={searchInput} onChange={handleSearchInput}></input>
</header>)
}