Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native: Position child element relative to device and not parent

Tags:

react-native

I have a child element <Child /> inside <Parent height="40"/> I want to absolutely position child element relative to device view area and not parent.

example layout

<device height="1000">

 <header height="500">
 <ScrollView />
 <parent height=40">
  <child height="300" top="150" />
 </parent>


</device>

position="absolute" is relative to parent and there is no position="fixed"

like image 290
rendom Avatar asked Oct 16 '22 08:10

rendom


1 Answers

Relative : Relative to it’s current position, but can be moved. Or A RELATIVE positioned element is positioned relative to ITSELF.

Absolute : In React Native, an ABSOLUTE positioned element is positioned relative to IT'S CLOSEST PARENT. If that parent happens to be a box that covers the entire viewport of your device, then it works like fixed (the child can be positioned relative to the device). Better explanation here from the docs.

What the official docs recommends (seen in above link): If you want to position a child relative to something that is not its parent [in your case it would be the device viewport], don't use styles for that. Use the component tree. For that see solution #2.

Solution 1:

here is a demo: https://snack.expo.io/@nomi9995/7ee9c4

you can use the Portal from react-native-paper to position child compoent from device not from parent

import * as React from "react";
import { View, StyleSheet } from "react-native";
import { Portal, Text, Provider as PaperProvider } from "react-native-paper";

const Child=()=>{
return (
  <Text>This is Child component which take positioned from Parent</Text>
    )
}
class App extends React.Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <View style={styles.container}>
          <Portal>
            <Child />
          </Portal>
        </View>
      </View>
    );
  }
  Î;
}

const styles = StyleSheet.create({
  container: {
    justifyContent: "center",
    alignItems: "center",
    flex: 1,
    backgroundColor: "#eee",
  },
});

const JSX = () => {
  return (
    <PaperProvider>
      <App />
    </PaperProvider>
  );
};

export default JSX;

Solution 2:

place Child outside of parent and give position:"absolute"

like this

<device height="1000">

 <header height="500">
 <ScrollView />
 <parent height=40">
 </parent>

 <child height="300" style={{position:"absolute",top:150}} />

</device>
like image 192
Muhammad Numan Avatar answered Oct 21 '22 04:10

Muhammad Numan