r/reactjs • u/NoTutor4458 • Jul 19 '26
how to rerender component on variable change?
new to react, so providing either corrected code or just concept that i should look into would be helpful :)
i want to change height of the app when phone keyboard uppears so it doesnt overlay on website by using VisualViewport API.
i am sure only thing that i have to do now is to rerender component when height is changed, so how can i do that?
export default function NewChat() {
return (
<div
className={styles.wrapper}
style={{ height: `${visualViewport?.height}px` }}
>
<Prompt />
</div>
);
}
9
Upvotes
26
u/Krimson1911 Jul 19 '26 edited Jul 19 '26
React will only rerender when React state or props change. Not some external state like height. IOW reading "visualViewport.height" directly does not tell React that it changed.
Store the height in state, then listen for the viewport "resize" event:
Calling
setHeight()updates React state, which causes the component to rerender.You may also be able to solve this with CSS using:
"dvh" is the dynamic viewport height and usually adjusts when the mobile keyboard or browser UI changes.The CSS approach is worth trying first since it avoids JavaScript entirely.
3
u/DontThrowMeAway43 Jul 19 '26
Why dont you use CSS for that ? Size of the viewport is just
100dvh?Or am I missing something ?
1
u/artem1458 Jul 19 '26
https://react.dev/learn/tutorial-tic-tac-toe#passing-data-through-props
1
u/lightfarming Jul 19 '26
the only answer you should losten to for this, is that this type of thing should be pure css. no javascript should be involved at all.
3
u/ISDuffy Jul 19 '26
Viewport wise this possible could just be CSS.
The other option would be to have use hook that uses a resize observer and can undate a state.
1
u/Kautsu-Gamer Jul 20 '26
You must create state or property change, which is really annoying.
Due this keep boolean variable useState if you need refresh, and trigger it with state change.
-1
u/EncryptedPlays Jul 19 '26
i think you can do it by making the div it's own component, then passing visualViewport?.height into it like this
divComponent.js
mainComponent.js
-2
u/AcanthisittaNo5807 Jul 19 '26
Add “key” to the component
0
u/[deleted] Jul 19 '26
[deleted] — view deleted comment