Using position absolute in React Native
when to escape flex flow.
absolute removes a view from flex flow and positions it relative to its nearest positioned ancestor using top, left, right, bottom; ideal for overlays and badges.
WHAT THIS TESTS It checks that you know when to break out of the flexbox flow and how React Native's positioning model differs from the full web CSS model.
A GOOD ANSWER COVERS By default views use position relative and participate in the flex layout, affecting the size and position of siblings. Setting position absolute removes the view from that flow, so it no longer pushes siblings around, and you position it using the top, left, right, and bottom offsets. Those offsets are measured relative to the nearest ancestor that establishes a positioning context, which in practice is the parent View; if you give the parent position relative and overflow handling, the absolute child is placed within it. This is ideal when an element must layer on top of others rather than sit in the flow: a full-screen overlay or modal backdrop, a tooltip, a floating action button, or a count badge anchored to the top-right corner of an icon. React Native does not support position fixed, and there is no z-index cascade identical to the web, though zIndex and elevation control stacking.
COMMON WRONG ANSWERS Assuming absolute is relative to the screen rather than the parent. Expecting position fixed to exist. Forgetting the parent usually needs a defined size and position relative so the child anchors correctly.
LIKELY FOLLOW-UPS How do you control stacking order? How do you center an absolute overlay? What happens if no ancestor is positioned?
ONE CONCRETE EXAMPLE For an icon with an unread badge, you wrap the icon in a parent View with position relative and a fixed size. The badge is a small View with position absolute, top 0 and right 0, holding a Text count. It floats over the icon's corner without altering the icon's layout or shifting neighboring elements in the row.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.