I'm trying to dynamically pass the width to a component's styles. On first load, it's okay, but if I resize it never re renders the component, even though the hook is working.
I read about that since NextJs is server side rendering this can cause this client side's issues. So here's the code:
Hook
const useWidth = () => {
if (process.browser) {
const [width, setWidth] = useState(window.innerWidth);
const handleResize = () => setWidth(window.innerWidth);
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [width]);
return width;
}
return 0;
};
Component (reduced just to show the example)
const Login = () => {
const windowWidth = useWidth();
const width = windowWidth > CELLPHONE_WIDTH ? '36.6rem' : '90%';
const loginStyles = styles(width);
return (
<div className='container'>
<TextInput
type='text'
width={width}
placeholder='Email'
/>
</div>
);
};
Styles
function textInputStyles(width) {
return css`
width: ${width};
`;
}
export default textInputStyles;