React Native Portal View

react-native-portal-view

Features

  1. The effect similar to h5 position:‘fixed’ can be achieved
  2. There can be multiple root nodes that do not affect each other
  3. You can render a component to multiple root nodes at the same time

Installation

npm

npm i react-native-portal-view -S

yarn

yarn add react-native-portal-view

Component

PortalProvider

Provide a root node, which can be located anywhere in the component tree

Props
Name Default Value Type Description
maybeActive () => true function():boolean The return value represents whether the current Provider is active

Portal

Packed components will be rendered to all active PortalProviders

Props
Name Default Value Type Description
children void React.ReactNode Child Components
onMount void function(): void Portal componentDidMount trigger
onDestroy void function(): void Portal componentWillunmount trigger

Example

import * as React from'react';
import {View, Text, AppRegistry} from'react-native';
import {PortalProvider,Portal} from'react-native-portal-view';
import useToggle from'react-use/lib/useToggle';

function Modal(props) {
  return (
    <View style={styles.container}>
      <Text onPress={props.onPress} style={styles.text}>
        Portal example {props.text}, click to destroy
      </Text>
    </View>
  );
}

const ModalComponent = (props: any) => {
  return (
    <Portal onDestroy={() => console.log('onDestroy')} onMount={() => console.log('onMount')}>
      <Modal {...props} />
    </Portal>
  );
};

function App() {
  const [visible, toggle] = useToggle(false);
  const [activeKey, setActiveKey] = React.useState(1);

  return (
    <>
      <View style={styles.container}>
        <Text onPress={toggle}> {visible?'Destroy':'Create'}</Text>
        <Text
          onPress={() => {
            setActiveKey(activeKey === 1? 2: 1);
          }}
        >
          Switch provider
        </Text>
      </View>
      {visible && <ModalComponent onPress={toggle} text={`component ${activeKey}`} />}

      <View style={styles.portalProvider1}>
        <PortalProvider
          maybeActive={() => {
            return activeKey === 1;
          }}
        />
      </View>

      <View style={styles.portalProvider2}>
        <PortalProvider
          maybeActive={() => {
            return activeKey === 2;
          }}
        />
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems:'center',
    justifyContent:'center',
  },

  portalProvider1: {
    width: 300,
    height: 300,
    backgroundColor:'red',
  },
  portalProvider2: {
    width: 400,
    height: 400,
    backgroundColor:'blue',
  },
});

AppRegistry.registerComponent('example', () => App);

Download Details:

Author: liuyunjs

Source Code: https://github.com/liuyunjs/react-native-portal

#react #react-native #mobile-apps

React Native Portal View
4.75 GEEK