Giter Site home page Giter Site logo

react-native-modal / react-native-modal Goto Github PK

View Code? Open in Web Editor NEW
5.4K 39.0 612.0 9.3 MB

An enhanced, animated, customizable Modal for React Native.

License: MIT License

JavaScript 7.40% Java 4.52% Objective-C 6.71% Ruby 4.53% TypeScript 73.73% Starlark 3.11%
react-native react modal android ios backdrop animation animated

react-native-modal's Introduction

Announcements

  • 📣 We're looking for maintainers and contributors! See #598
  • 💡 We're brainstorming if/how we can make a JavaScript-only version of react-native-modal. See #597
  • 🙏 If you have a question, please start a new discussion instead of opening a new issue.

react-native-modal

npm version styled with prettier

If you're new to the React Native world, please notice that React Native itself offers a component that works out-of-the-box.

An enhanced, animated, customizable React Native modal.

The goal of react-native-modal is expanding the original React Native <Modal> component by adding animations, style customization options, and new features, while still providing a simple API.

Features

  • Smooth enter/exit animations
  • Plain simple and flexible APIs
  • Customizable backdrop opacity, color and timing
  • Listeners for the modal animations ending
  • Resize itself correctly on device rotation
  • Swipeable
  • Scrollable

Setup

This library is available on npm, install it with: npm i react-native-modal or yarn add react-native-modal.

Usage

Since react-native-modal is an extension of the original React Native modal, it works in a similar fashion.

  1. Import react-native-modal:
import Modal from "react-native-modal";
  1. Create a <Modal> component and nest its content inside of it:
function WrapperComponent() {
  return (
    <View>
      <Modal>
        <View style={{ flex: 1 }}>
          <Text>I am the modal content!</Text>
        </View>
      </Modal>
    </View>
  );
}
  1. Then, show the modal by setting the isVisible prop to true:
function WrapperComponent() {
  return (
    <View>
      <Modal isVisible={true}>
        <View style={{ flex: 1 }}>
          <Text>I am the modal content!</Text>
        </View>
      </Modal>
    </View>
  );
}

The isVisible prop is the only prop you'll really need to make the modal work: you should control this prop value by saving it in your wrapper component state and setting it to true or false when needed.

A complete example

The following example consists in a component (ModalTester) with a button and a modal. The modal is controlled by the isModalVisible state variable and it is initially hidden, since its value is false.
Pressing the button sets isModalVisible to true, making the modal visible.
Inside the modal there is another button that, when pressed, sets isModalVisible to false, hiding the modal.

import React, { useState } from "react";
import { Button, Text, View } from "react-native";
import Modal from "react-native-modal";

function ModalTester() {
  const [isModalVisible, setModalVisible] = useState(false);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  return (
    <View style={{ flex: 1 }}>
      <Button title="Show modal" onPress={toggleModal} />

      <Modal isVisible={isModalVisible}>
        <View style={{ flex: 1 }}>
          <Text>Hello!</Text>

          <Button title="Hide modal" onPress={toggleModal} />
        </View>
      </Modal>
    </View>
  );
}

export default ModalTester;

For a more complex example take a look at the /example directory.

Available props

Name Type Default Description
animationIn string or object "slideInUp" Modal show animation
animationInTiming number 300 Timing for the modal show animation (in ms)
animationOut string or object "slideOutDown" Modal hide animation
animationOutTiming number 300 Timing for the modal hide animation (in ms)
avoidKeyboard bool false Move the modal up if the keyboard is open
coverScreen bool true Will use RN Modal component to cover the entire screen wherever the modal is mounted in the component hierarchy
hasBackdrop bool true Render the backdrop
backdropColor string "black" The backdrop background color
backdropOpacity number 0.70 The backdrop opacity when the modal is visible
backdropTransitionInTiming number 300 The backdrop show timing (in ms)
backdropTransitionOutTiming number 300 The backdrop hide timing (in ms)
customBackdrop node null The custom backdrop element
children node REQUIRED The modal content
deviceHeight number null Device height (useful on devices that can hide the navigation bar)
deviceWidth number null Device width (useful on devices that can hide the navigation bar)
isVisible bool REQUIRED Show the modal?
onBackButtonPress func () => null Called when the Android back button is pressed
onBackdropPress func () => null Called when the backdrop is pressed
onModalWillHide func () => null Called before the modal hide animation begins
onModalHide func () => null Called when the modal is completely hidden
onModalWillShow func () => null Called before the modal show animation begins
onModalShow func () => null Called when the modal is completely visible
onSwipeStart func () => null Called when the swipe action started
onSwipeMove func (percentageShown) => null Called on each swipe event
onSwipeComplete func ({ swipingDirection }) => null Called when the swipeThreshold has been reached
onSwipeCancel func () => null Called when the swipeThreshold has not been reached
panResponderThreshold number 4 The threshold for when the panResponder should pick up swipe events
scrollOffset number 0 When > 0, disables swipe-to-close, in order to implement scrollable content
scrollOffsetMax number 0 Used to implement overscroll feel when content is scrollable. See /example directory
scrollTo func null Used to implement scrollable modal. See /example directory for reference on how to use it
scrollHorizontal bool false Set to true if your scrollView is horizontal (for a correct scroll handling)
swipeThreshold number 100 Swiping threshold that when reached calls onSwipeComplete
swipeDirection string or array null Defines the direction where the modal can be swiped. Can be 'up', 'down', 'left, or 'right', or a combination of them like ['up','down']
useNativeDriver bool false Defines if animations should use native driver
useNativeDriverForBackdrop bool null Defines if animations for backdrop should use native driver (to avoid flashing on android)
hideModalContentWhileAnimating bool false Enhances the performance by hiding the modal content until the animations complete
propagateSwipe bool or func false Allows swipe events to propagate to children components (eg a ScrollView inside a modal)
style any null Style applied to the modal

Frequently Asked Questions

The component is not working as expected

Under the hood react-native-modal uses react-native original Modal component.
Before reporting a bug, try swapping react-native-modal with react-native original Modal component and, if the issue persists, check if it has already been reported as a react-native issue.

The backdrop is not completely filled/covered on some Android devices (Galaxy, for one)

React-Native has a few issues detecting the correct device width/height of some devices.
If you're experiencing this issue, you'll need to install react-native-extra-dimensions-android.
Then, provide the real window height (obtained from react-native-extra-dimensions-android) to the modal:

const deviceWidth = Dimensions.get("window").width;
const deviceHeight =
  Platform.OS === "ios"
    ? Dimensions.get("window").height
    : require("react-native-extra-dimensions-android").get(
        "REAL_WINDOW_HEIGHT"
      );

function WrapperComponent() {
  const [isModalVisible, setModalVisible] = useState(true);

  return (
    <Modal
      isVisible={isModalVisible}
      deviceWidth={deviceWidth}
      deviceHeight={deviceHeight}
    >
      <View style={{ flex: 1 }}>
        <Text>I am the modal content!</Text>
      </View>
    </Modal>
  );
}

How can I hide the modal by pressing outside of its content?

The prop onBackdropPress allows you to handle this situation:

<Modal
  isVisible={isModalVisible}
  onBackdropPress={() => setModalVisible(false)}
>
  <View style={{ flex: 1 }}>
    <Text>I am the modal content!</Text>
  </View>
</Modal>

How can I hide the modal by swiping it?

The prop onSwipeComplete allows you to handle this situation (remember to set swipeDirection too!):

<Modal
  isVisible={isModalVisible}
  onSwipeComplete={() => setModalVisible(false)}
  swipeDirection="left"
>
  <View style={{ flex: 1 }}>
    <Text>I am the modal content!</Text>
  </View>
</Modal>

Note that when using useNativeDriver={true} the modal won't drag correctly. This is a known issue.

The modal flashes in a weird way when animating

Unfortunately this is a known issue that happens when useNativeDriver=true and must still be solved.
In the meanwhile as a workaround you can set the hideModalContentWhileAnimating prop to true: this seems to solve the issue. Also, do not assign a backgroundColor property directly to the Modal. Prefer to set it on the child container.

The modal background doesn't animate properly

Are you sure you named the isVisible prop correctly? Make sure it is spelled correctly: isVisible, not visible.

The modal doesn't change orientation

Add a supportedOrientations={['portrait', 'landscape']} prop to the component, as described in the React Native documentation.

Also, if you're providing the deviceHeight and deviceWidth props you'll have to manually update them when the layout changes.

I can't show multiple modals one after another

Unfortunately right now react-native doesn't allow multiple modals to be displayed at the same time. This means that, in react-native-modal, if you want to immediately show a new modal after closing one you must first make sure that the modal that your closing has completed its hiding animation by using the onModalHide prop.

I can't show multiple modals at the same time

See the question above. Showing multiple modals (or even alerts/dialogs) at the same time is not doable because of a react-native bug. That said, I would strongly advice against using multiple modals at the same time because, most often than not, this leads to a bad UX, especially on mobile (just my opinion).

The StatusBar style changes when the modal shows up

This issue has been discussed here.
The TLDR is: it's a know React-Native issue with the Modal component 😞

The modal is not covering the entire screen

The modal style applied by default has a small margin.
If you want the modal to cover the entire screen you can easily override it this way:

<Modal style={{ margin: 0 }}>...</Modal>

I can't scroll my ScrollView inside of the modal

Enable propagateSwipe to allow your child components to receive swipe events:

<Modal propagateSwipe>...</Modal>

Please notice that this is still a WIP fix and might not fix your issue yet, see issue #236.

The modal enter/exit animation flickers

Make sure your animationIn and animationOut are set correctly.
We noticed that, for example, using fadeIn as an exit animation makes the modal flicker (it should be fadeOut!). Also, some users have noticed that setting backdropTransitionOutTiming={0} can fix the flicker without affecting the animation.

The custom backdrop doesn't fill the entire screen

You need to specify the size of your custom backdrop component. You can also make it expand to fill the entire screen by adding a flex: 1 to its style:

<Modal isVisible={isModalVisible} customBackdrop={<View style={{ flex: 1 }} />}>
  <View style={{ flex: 1 }}>
    <Text>I am the modal content!</Text>
  </View>
</Modal>

The custom backdrop doesn't dismiss the modal on press

You can provide an event handler to the custom backdrop element to dismiss the modal. The prop onBackdropPress is not supported for a custom backdrop.

<Modal
  isVisible={isModalVisible}
  customBackdrop={
    <TouchableWithoutFeedback onPress={dismissModalHandler}>
      <View style={{ flex: 1 }} />
    </TouchableWithoutFeedback>
  }
/>

Available animations

Take a look at react-native-animatable to see the dozens of animations available out-of-the-box. You can also pass in custom animation definitions and have them automatically register with react-native-animatable. For more information on creating custom animations, see the react-native-animatable animation definition schema.

Alternatives

Acknowledgements

Thanks @oblador for react-native-animatable, @brentvatne for the npm namespace and to anyone who contributed to this library!

Pull requests, feedbacks and suggestions are welcome!

react-native-modal's People

Contributors

alex-blair avatar alimek avatar ancyrweb avatar andrew avatar calardotco avatar cjroth avatar dependabot[bot] avatar egorhlebnikoff avatar g3r4n avatar g3z avatar hbarylskyi avatar ifsnow avatar ionut-movila avatar iroachie avatar jkomyno avatar kenyontu avatar mmazzarolo avatar nickersoft avatar peteroid avatar pistonsky avatar purii avatar reime005 avatar richardlindhout avatar samin avatar sandersn avatar semantic-release-bot avatar springltd avatar stackia avatar tomasreimers avatar yairk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-modal's Issues

Opening a Modal from a Modal

<Modal isVisible={this.props.isFirstModalVisible}>
    <View>
        <TouchableOpacity onPress={() => this.props.showSecondModal()}>
               <Text>{'show second modal'}</Text>
         </TouchableOpacity>
    </View>
</Modal>

<Modal isVisible={this.props.isSecondModalVisible}>
    <View>
        <Text>{'Hello World'}</Text>
    </View>
</Modal>

<TouchableOpacity onPress={() => this.props.showFirstModal()}>
     <Text>{'show first modal'}</Text>
</TouchableOpacity>

second modal doesn't open, i'm using redux
plz help

How do you open the example?

Hi,

I must be doing something wrong, but I can't seem to get the example working.

git clone https://github.com/react-native-community/react-native-modal
cd react-native-modal/example
npm install && react-native run-ios

does not seem to be working for me. Can someone else confirms that it works for them so I can look into a my system specific bug?

Thanks,
Tomas

onBackdropPress not functioning as expected on Android

So I've been trying to use the newly implemented onBackdropPress to close a modal when the backdrop is pressed. As it wasn't working originally, I decided to replace the functionality with a console log to see when onBackdropPress is being called.

From what I can see, the only times it's firing off are when I open the modal originally, and when I close the modal using onBackButtonPress. Nothing seems to be triggered when I tap the modal itself.

I've attempted to move the modal to different levels in component structure (I have a number of child components and ideally wanted to call it from the very last child), but it seems to function the same regardless of where it is.

My usage of the modal looks like this:

<Modal
    isVisible = {this.props.visible}
    backdropColor = 'red'
    onBackdropPress = {console.log("Pressed")}
    onBackButtonPress = {this.props.closeModal}>
    <View style = {styles.modalView}>
        ...
    </View>
</Modal>

Dependencies in use:
react-native-modal 3.1.0.
react 16.0.0-alpha.12
react-native 0.47.2

I'm running on a Samsung Galaxy S5.

Here's a link to a basic expo app which shows the issue: https://github.com/vanhoutk/modaltest

How to do fade in fade out animation?

Hi, any idea to better fade in and fade out? i didn't find the reference for fade animation so now we are currently modified the animations.js with fadeIn and fadeOut entry that modify opacity props like this

function makeFadeTransition(transitionType, fromValue, toValue){
  return {
    from: {
      [transitionType]: fromValue,
    },
    to: {
      [transitionType]: toValue,
    },
  };
}
export const fadeIn = makeFadeTransition('opacity', 0, 1);

export const fadeOut = makeFadeTransition('opacity', 1, 0);

Executing function when showing or hiding modal as soon as possible

Currently, there is onModalShow and onModalHide that allows to execute function. One of their downsides is that they execute passed function once the animation finishes. This makes it difficult to create synchronous animation.

Here's example below:
onmodalhide

The plus button changes colour after the modal is hidden. In my opinion, this doesn't create a smooth animation.

Here's my proposal:
onmodalhideearly

The plus button changes colour almost immediately with the modal creating a seamless effect. This creates a much better UI experience in my opinion.

Here's how I have achieved this effect:

  _close = async () => {
    this.props.onModalHideEarly();
    this.backdropRef.transitionTo({ opacity: 0 }, this.props.backdropTransitionOutTiming);
    this.contentRef[this.props.animationOut](this.props.animationOutTiming).then(() => {
      this.setState({ isVisible: false });
      this.props.onModalHide();
    });
  };

Ps. this is only a part of the commit.

I have forked the repo and can submit a PR request if you think this enhancement is worthwhile.

Modal margin improvement ?

Hi,
First of all, thanks for this very useful package !

I just wanted to point out that the margin of the modal's content (deviceWidth * 0.05) seems to be problematic in some case (at least in mine, with the latest android emulator).

I noticed that since the margin value is not rounded, I sometimes get a "blank" pixel that I can't fill (for example, when trying to make some buttons at the bottom).
It can be simply solved by using a custom margin of Math.round(deviceWidth * 0.05), and I thought that maybe it would be interesting to put it directly in the package !

I am using the last version (3.0.2) with react-native 0.47.1. The "problem" appears on the emulator with android 7.0.

I enclosed some pictures to help visualize what I meant :

margin_not_rounded
Here with the current margin

 

margin_rounded
Here with the rounded margin (no more white pixel line at the bottom).

Bye

PS : if this behavior is intended, please forgive me for the disturbance.

Cannot Style like First Example

I love the style and animations of the first gif example (from the left) that you have on the README. I am unable to get the animations to work correctly though. For some reason the default animations do not start from or return to the bottom of the screen like they do in your example. I am able to add a margin to the top so I can center the modal in the screen but when it slides up it doesn't come up from the bottom of the screen. When the modal dismisses it does not slide down past the bottom of the screen. The modal slides down or up for what looks like 100-200 pixels and then pops in or away. It is quite jarring of an animation.

Navigation between screens with a button displayed in <Modal />

Hello everyone.

I'm displaying a button inside Modal, but when I click the button and navigate between the screens, the modal continues to be displayed.

I would like that when you click a button, is closed.
Is there any way to do this?

SCREEN I:
error i

SCREEN II:
error ii

Avoid keyboard

How can I avoid the keyboard with the modal? I tried KeyboardAvoidingView but that doesn't seem to do anything

Android issue for multiple modals

my current version: v2.4.0

Attached the screenshots, on testing with the example.

If we close the modal by pressing android back button instead of the close button, warning message will be shown when we open another modal.

After quick checking on source code, I made the following workaround, but I am not sure if it will break other behaviour.

  _close = async () => {
    if (this.state.isVisible) {
      this.backdropRef.transitionTo({ opacity: 0 }, this.props.backdropTransitionOutTiming);
      this.contentRef[this.props.animationOut](this.props.animationOutTiming).then(() => {
        this.setState({ isVisible: false });
        this.props.onModalHide();
      });
    }
  };

test
test2

A way to specify no animation

is there a way to specify no animation? I would like to be able to have no animation (so it just appears) for showing the modal, and slide out for hiding the modal

The statusbar turns white when the modal is open (only on certain devices)

I have a component with status bar set to hidden like this:

<View style={ style.container } >
   <StatusBar hidden={true} />

        ...
        
   <Modal isVisible={this.state.isModalVisible}>
     <Text>Modal</Text>   
   </Modal>

</View>

When the modal is visible, status bar is hidden but instead there is an empty white block at the top with the exact height of the status bar:

screenshot

react-native : 0.45.1
react-native-moda l: 2.5.0
android : 5.1.1

Have modal not take up entire viewable screen: QUESTION

Looking to use this but constrained within a limited part of the screen rather than the entire viewable screen, perhaps this is an oxymoron of using a modal?

I've given the modal specific sizing but it ignores it and still takes up the entire UI.

Two modals at the same time

Is it possible to have two modals open on top of each other? Right now if I try to render two modals at the same time it just renders the first one.

Tap outside to close

Is there a way to implement that function? Right now when I tap on the darkened region, the modal doesn't close.

Multiple modals not working in react native

When tapping on first modal window i need to open a second modal to the user. i implemented the same but the second modal not opening. Sometime it opens and disappears. any suggestions would be helpful.

Android back button callback?

By default, the Android Back button will close the modal. Looking at the code I found the (undocumented?) hideOnBack property which disabled this.

The behavior I'm after is a bit different: I'm presenting the user with an alert modal, on top of an existing scene, that will explain what needs to be done. What I'd like to happen is that if Back is pressed, then the app will navigate to the earlier scene (i.e. not just close the modal and stay at the same scene, but go back to the previous scene).

I was hoping that a close callback would allow me to do this (by simulating a Back press), but I don't think I can tell whether the modal was closed as a result of the Back button or not. Is there a way to achieve this?

How to create a drop-down modal menu?

I figured that I would to precisely determine the position of the modal, so that when it appears, it appears right below the button which opens it. How should I approach it with react-native-modal? Thanks!

Is it possible to set animatable V1.1.1 in dependencies?

Hi,
First, thanks you for this awesome module !
This module uses animatable 0.6.1 as dependency.

Is it possible to switch to 1.1.1 ?
It permit to define custom animations via Animatable.initializeRegistryWithDefinitions :)

Thx !

Modal does not appear

I am trying to get a simple modal to appear on screen using RN v0.40.0. I have imported the animated modal using

import Modal from 'react-native-animated-modal';

and have inserted a modal component into my view:

 <View>
              <Text style={{marginTop: 80}}>Hello</Text>
               
               <Modal
                isVisible={true}
               >
               <Navigator
                initialRoute={{ title: 'SignUp', index: 0 }}
                renderScene={(route, navigator) =>
                  <SignUp onModalClose={this.onModalClose.bind(this)} />
                }
                />
               </Modal>
</View>

The modal does not appear.

However, I have found that by changing isVisible to the regular react-native prop visible and running my app, a normal non animating modal appears. After that, I can change the visibleProp back to the animatedModal prop isVisible, and get an animated modal to appear the first time running the app, but it does not appear on subsequent runs.

For example, I change isVisible to visible:

<Modal
                visible={true}
               >

Then run the app. A regular react native modal appears with my views in it.

After that, I change visible back to isVisible

<Modal
                isVisible={true}
               >

and run the app again. this time the animated modal appears correctly this one and only run. However if I refresh the app in the simulator, the modal does not appear on subsequent runs. Any ideas how to solve this?

modal in front of a modal

Hey,
In my app, i need to open a new modal in front of an existing modal, but i couldn't make it work...

Add more demo images to the README

Hello everyone!
If you're interested, you can submit here a gif/video/info of your react-native-modal in action and I'll add it to the README.md and credit section 🌴

custom component wrapper for Modal

I am trying to create a customized modal for error validation alerts, so I know it is a single button "click to close" pattern of popup and I have styling and can pass in the message and visibility things as props. Instead of creating that each time I wanted to just have a custom modal, but I am not able to do so without errors saying.

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function but got : undefined. You likely forgot to export your component form the file it's defined in. Check the render method of 'ModalValidationCustom'

also getting
ossible Unhandled Promise Rejection (id: 0): Cannot read property 'transitionTo' of undefined TypeError: Cannot read property 'transitionTo' of undefined at AnimatedModal._callee$

Sample Code of exponent i am exporting

class ModalValidationCustom extends Component{
  constructor(props){
    super(props)
    this.state={
      isVisible:false
    }
    this.handleClose = this.handleClose.bind(this)
  }
  handleClose=()=>{
    if(this.props.handleClose)
      this.props.handleClose()
    else
      console.log("make a handleclose prop function to set state")
  }
  
  render(){
        return(
          <Modal animationIn='zoomIn' animationOut='zoomOut' isVisible={this.props.isVisible || this.state.isVisible}>
            <View style={[styles.center,{ flex: 0,padding:20,borderRadius:10,justifyContent:'space-around', backgroundColor:'#fff' }]}>
              
              <Text style={{marginVertical:15, color:colors.sec_color}}>{this.props.modal_message}</Text>

              <Button 
              title="OK"
              onPress={this.handleClose}
              />
            </View>
        </Modal>
        )
  }
}

@mmazzarolo

backdropColor not showing on Samsung S6

Hi people! I'm having a weird issue. If I run my application on a Samsung S6 with Android 7.0.0 the backdropColor is not showing.
screenshot_20170818-101016

I've tried the same app in an iOS 10.3 simulator and is doing good. I also tried it in the following Android devices and it's also doing good:

  • HTC Desire, Android 4.4.2

  • Nexus 5, Android 6.0.0

  • Nexus 5, Android 7.0.0

Do you know what's going on?

"react": "16.0.0-alpha.6",
"react-native": "0.44.0",
"react-native-modal": "^2.5.0",

Device rotation issues

I've encountered two issues while using this component over the regular modal:

  1. I had to add supportedOrientations={['portrait', 'landscape']} prop in order for rotation to actually work (which is not documented anywhere).
  2. After doing so, and rotating the device, the black background isn't covering the entire screen anymore

Advice on mocking animations

Hello, first off, thanks for an awesome component!

We're trying to create a snapshot test using Jest for a component that uses react-native-modal. Upon running, it errors on initializeRegistryWithDefinitions.

nomock

We then tried mocking it with

import { View } from 'react-native';

const initializeRegistryWithDefinitions = jest.fn();
export {
  View,
  initializeRegistryWithDefinitions
};

which gave another error.
image

Any advice on what is the correct way to mock this? Ultimately I know we have to mock react-native-animatable which I already am doing above without initializeRegistryWithDefinitions :)

No animationOut instead of slideOutDown

I've got a really strange behavior with this library and react-native 0.48. I am using the modal with default props. When I open the modal it properly uses the slideInUp animation. When I close the modal no animation is used even though it should be slideOutDown by default. Strangely - when I open the modal, then put the app into background, open the app again and close the modal afterwards - it will properly use the slideOutDown animation 🤔

Edit how far the modal exits

Is there a way to edit how far the modal exits? If I alter the size of the modal and I call hideModal, the modal itself drops a few, then abruptly disappears

Native error on hide

The message is:

The specified child already has a parent. You must call removeView() on the child’s parent first.

I'm seeing this whenever I hide the modal. I'm not sure if the modal causes this, I'm just really hoping someone sees this error and goes "oh, yeah you're just being stupid. Do <42> to solve your problem".

This only happens on android and works fine on ios.

addViewInner
    ViewGroup.java:4417
addView
    ViewGroup.java:4258
addView
    ViewGroup.java:4198
addView
    ReactViewManager.java:209
addView
    ReactViewManager.java:41
manageChildren
    NativeViewHierarchyManager.java:394
execute
    UIViewOperationQueue.java:179
run
    UIViewOperationQueue.java:787
flushPendingBatches
    UIViewOperationQueue.java:843
access$1600
    UIViewOperationQueue.java:48
doFrameGuarded
    UIViewOperationQueue.java:889
doFrame
    GuardedFrameCallback.java:31
doFrame
    ReactChoreographer.java:129
doFrame
    ChoreographerCompat.java:107
run
    Choreographer.java:872
doCallbacks
    Choreographer.java:686
doFrame
    Choreographer.java:618
run
    Choreographer.java:860
handleCallback
    Handler.java:751
dispatchMessage
    Handler.java:95
loop
    Looper.java:154
main
    ActivityThread.java:6119
invoke
    Method.java:-2
run
    ZygoteInit.java:886
main
    ZygoteInit.java:776

Put modal and its content under (zIndex) Header?

Hi, I am working on a project and am finding it very difficult to get the modal to be put underneath (in a zIndex / elevation manner) the Header that I have. The header is in Native Base so I don't know if this is an issue with Native Base or react-native-modal.

image

That is what it currently looks like and it seems that no matter how I adjust the zIndex or elevation of the components, I cannot get anything to really go on-top of the modal... any help would be appreciated.

Any way to specify custom animations?

Hey guys, great library! I'm currently calling initializeRegistryWithDefinitions() on Animatable with my own animations, and tried using them in the "animationIn" and "animationOut" props of this modal. While it seems to work fine on iOS, I get the following error when running it on my Android device:

09-19 00:39:45.111  6186  6216 E ReactNativeJS: undefined is not a function (evaluating '_this.contentRef[_this.props.animationIn](_this.props.animationInTiming)')

Which basically suggests that my animation isn't initialized by the time the modal appears, despite initializeRegistryWithDefinitions() already being called. Any reason there would be such a behavioral difference between platforms?

Not able to Trigger Android BackButton Action, when Modal is opened.

I am not able to trigger Android BackButton when modal is opened.
Here is my code

BackAndroid.addEventListener("hardwareBackPress", () => {
	Alert.alert("Sample", "Backbutton Pressed");
	if(this.state.isModalVisible) {
		this.setState({isModalVisible: false});
                return true
	}
	else {
		if (this.props.navigator.getCurrentRoutes().length > 1) {
			this.props.navigator.pop()
			return true
		} else {
			return false
		}
	}
})

black screen on Android

using it with flatlist

 <Card 
                    containerStyle={{borderColor: 'transparent'}}>

                    <ListItem
                      badge={{ value: 3, badgeTextStyle: { color: 'red' }, badgeContainerStyle: { marginTop: 10, color:'orange' } }}
                      roundAvatar
                      title={`${item.name.first} ${item.name.last}`}
                      subtitle={item.email}
                      avatar={
                        <TouchableOpacity onPress ={ () => this._showModal()  }>
                        <Avatar
                        medium
                       // onPress ={ () => this._showModal()  }
                        rounded
                        source={{ uri: item.picture.thumbnail }} 
                      // style={{borderRadius:25, height:50, width:50 }}
                         />
                         </TouchableOpacity>
                             }
                    
                      containerStyle={{borderBottomWidth: 0, padding:0 }}
                    />
                    <Modal isVisible={this.state.isModalVisible}>
                      <View>
                        <Text>Hello!</Text>
                      </View>
                   </Modal>
                   
      </Card>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.