Giter Site home page Giter Site logo

expo / react-native-action-sheet Goto Github PK

View Code? Open in Web Editor NEW
1.3K 10.0 219.0 22.29 MB

A cross-platform ActionSheet for React Native

License: MIT License

JavaScript 0.50% TypeScript 99.50%
hacktoberfest react-native android expo ios actionsheet

react-native-action-sheet's Introduction

@expo/react-native-action-sheet

npm License: MIT Discord

React Native Action Sheet is a cross-platform React Native component that uses the native UIActionSheet on iOS and a pure JS implementation on Android.

iOS Android Web

Installation

npm install @expo/react-native-action-sheet

or

yarn add @expo/react-native-action-sheet

A basic ActionSheet Setup

1. Wrap your top-level component with <ActionSheetProvider />

ReactNativeActionSheet uses React context to allow your components to invoke the menu. This means your app needs to be wrapped with the ActionSheetProvider component first.

import { ActionSheetProvider } from '@expo/react-native-action-sheet';

export default function AppContainer() {
  return (
    <ActionSheetProvider>
      <App />
    </ActionSheetProvider>
  );
}

2. Call the showActionSheetWithOptions method with a hook or a higher order component.

// Using the provided hook
import { useActionSheet } from '@expo/react-native-action-sheet';

export default Menu() {
  const { showActionSheetWithOptions } = useActionSheet();

  const onPress = () => {
    const options = ['Delete', 'Save', 'Cancel'];
    const destructiveButtonIndex = 0;
    const cancelButtonIndex = 2;

    showActionSheetWithOptions({
      options,
      cancelButtonIndex,
      destructiveButtonIndex
    }, (selectedIndex: number) => {
      switch (selectedIndex) {
        case 1:
          // Save
          break;

        case destructiveButtonIndex:
          // Delete
          break;

        case cancelButtonIndex:
          // Canceled
      }});
  }

  return (
    <Button title="Menu" onPress={onPress}/>
  )
};

Alternatively, any component can use the higher order component to access the context and pass the showActionSheetWithOptions as a prop.

// Using a Higher Order Component to wrap your component
import { connectActionSheet } from '@expo/react-native-action-sheet';

function Menu({ showActionSheetWithOptions }) {
  /* ... */
}

export default connectActionSheet(Menu);

Menu component can now access the actionSheet prop as showActionSheetWithOptions.

Options

The goal of this library is to mimic the native iOS and Android ActionSheets as closely as possible.

This library can also be used in the browser with Expo for web.

Universal Props

Name Type Description
options array of strings A list of button titles (required)
cancelButtonIndex number Index of cancel button in options
cancelButtonTintColor string Color used for the change the text color of the cancel button
destructiveButtonIndex number or array of numbers Indices of destructive buttons in options
title string Title to show above the action sheet
message string Message to show below the title
tintColor string Color used for non-destructive button titles
disabledButtonIndices array of numbers Indices of disabled buttons in options

iOS Only Props

Name Type Description
anchor number iPad only option that allows for docking the action sheet to a node. See ShowActionSheetButton.tsx for an example on how to implement this.
userInterfaceStyle string The interface style used for the action sheet, can be set to light or dark, otherwise the default system style will be used.

Custom Action Sheet Only (Android/Web) Props

The below props allow modification of the Android ActionSheet. They have no effect on the look on iOS as the native iOS Action Sheet does not have options for modifying these options.

Name Type Description
icons array of required images or icons Show icons to go along with each option. If image source paths are provided via require, images will be rendered for you. Alternatively, you can provide an array of elements such as vector icons, pre-rendered Images, etc.
tintIcons boolean Icons by default will be tinted to match the text color. When set to false, the icons will be the color of the source image. This is useful if you want to use multicolor icons. If you provide your own nodes/pre-rendered icons rather than required images in the icons array, you will need to tint them appropriately before providing them in the array of icons; tintColor will not be applied to icons unless they are images from a required source.
textStyle TextStyle Apply any text style props to the options. If the tintColor option is provided, it takes precedence over a color text style prop.
titleTextStyle TextStyle Apply any text style props to the title if present.
messageTextStyle TextStyle Apply any text style props to the message if present.
autoFocus boolean If true, this will give the first option screen reader focus automatically when the action sheet becomes visible. On iOS, this is the default behavior of the native action sheet.
showSeparators boolean Show separators between items. On iOS, separators always show so this prop has no effect.
containerStyle ViewStyle Apply any view style props to the container rather than use the default look (e.g. dark mode).
separatorStyle ViewStyle Modify the look of the separators rather than use the default look.
useModal boolean Defaults to false (true if autoFocus is also true) Wraps the ActionSheet with a Modal, in order to show in front of other Modals that were already opened (issue reference).
destructiveColor string Modify color for text of destructive option. Defaults to #d32f2f.

ActionSheetProvider Props

The following props can be set directly on the ActionSheetProvider

Name Type Description
useCustomActionSheet boolean iOS only prop that uses the custom pure JS action sheet (Android/Web version) instead of the native ActionSheetIOS component. Defaults to false.
useNativeDriver boolean Windows only option that provides the option to disable the native animation driver for React Native Windows projects targeting Windows 10 Version-1809 ; Build-10.0.17763.0 and earlier. useNativeDriver is supported in Version-1903 and later so if your project is targeting that, you don't need to set this prop.
// example of using useCustomActionSheet on iOS
export default function AppContainer() {
  return (
    <ActionSheetProvider useCustomActionSheet={true}>
      <App />
    </ActionSheetProvider>
  );
}

Callback

The second parameter of the showActionSheetWithOptions function is a callback for when a button is selected. The callback takes a single argument which will be the zero-based index of the pressed option. You can check the value against your cancelButtonIndex to determine if the action was cancelled or not.

function onButtonPress(selectedIndex: number) {
  // handle it!
}

Try it out

Try it in Expo Snack: https://snack.expo.dev/@expo-action-sheet/example.

Example

See the example app.

Usage

$ cd example
$ yarn

// build simulator
$ yarn ios
$ yarn android

// web
$ yarn web

Development

Setup

$ git clone [email protected]:expo/react-native-action-sheet.git
$ cd react-native-action-sheet
$ yarn

Build

We use bob.

$ yarn build

Lint & Format

// tsc
$ yarn type-check

// ESLint + Prettier
$ yarn lint

react-native-action-sheet's People

Contributors

bradbumbalough avatar bradbyte avatar brentvatne avatar colinux avatar dependabot[bot] avatar evanbacon avatar expbot avatar henrikra avatar ide avatar jesseruder avatar jrichardlai avatar jstheoriginal avatar kamui545 avatar keima avatar kesha-antonov avatar kfiroo avatar mitch528 avatar naturalclar avatar nissy-dev avatar omerman avatar peterpme avatar quinlanj avatar semantic-release-bot avatar sfuqua avatar sibelius avatar simek avatar simenb avatar swordsman-inaction avatar terribleben avatar wsxyeah 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

react-native-action-sheet's Issues

Declarative API

Is there any way we can make the API more declarative and not require a top level ActionSheet wrapper?

Publish new version to npm

The version on npm (0.4.0) is crashing due to React.PropTypes.any code on ActionSheetProvider.js file.

This is weird because it was published 2 weeks ago and the fix in on master long before that.

But this is the content I'm getting on node_modules for the latest version:

import React from 'react';
import ActionSheet from './ActionSheet';

export default class ActionSheetProvider extends React.Component {
  static propTypes = {
    children: React.PropTypes.any,
  };

  static childContextTypes = {
    showActionSheetWithOptions: React.PropTypes.func,
  };

  getChildContext() {
    return {
      showActionSheetWithOptions: (...args) =>
        this._actionSheetRef.showActionSheetWithOptions(...args),
    };
  }

  render() {
    return (
      <ActionSheet ref={component => (this._actionSheetRef = component)}>
        {React.Children.only(this.props.children)}
      </ActionSheet>
    );
  }
}

simulator screen shot - iphone 8 - 2017-12-14 at 18 22 31

BackHandler should fall back to BackAndroid

Although BackHandler is now the standard, it is not present on older versions of react-native, so if you're using any react-native older than 0.44, there is a bug. There are two possible fixes:

  • Change the react-native version in package.json to only support react-native >= 0.44
  • Import BackHandler and BackAndroid, and if BackHandler is undefined, use BackAndroid as the handler.

Manual cancellation

I wanted to manual cancellation instead of automatic or wanted to do something before hiding? is there anyway?

Release v1.0.3?

Any plans on doing a new release? I would love to have the UI changes from #52 in my project.

Thanks a lot!

trying run with react-native-web

what I need to do to resolve following errors:

$ ./node_modules/.bin/webpack-dev-server --inline
 http://localhost:8080/
webpack result is served from /
content is served from /home/user/prj/aws
Hash: bafd29....
Version: webpack 1.14.0
Time: 5967ms
                               Asset     Size  Chunks             Chunk Names
ecc36ec57938da09da108791d013fa99.png  39.1 kB          [emitted]  
c839537124369420c473c24945961381.png   1.5 MB          [emitted]  
c57de438b49042b8766820d4ca865aec.png   153 kB          [emitted]  
79be0b6f1816000b571a8bfa8a8f4492.png  11.9 kB          [emitted]  
                           bundle.js  2.79 MB       0  [emitted]  main
chunk    {0} bundle.js (main) 2.66 MB [rendered]
    [0] multi main 40 bytes {0} [built]
....
  [782] ./components/ActivityIndicator.js 3.07 kB {0} [built]

ERROR in ./~/@exponent/react-native-action-sheet/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./ActionSheet in /home/user/prj/aws/node_modules/@exponent/react-native-action-sheet
 @ ./~/@exponent/react-native-action-sheet/index.js 1:16-40

ERROR in ./~/@exponent/react-native-action-sheet/ActionSheetProvider.js
Module parse failed: /home/user/prj/aws/node_modules/@exponent/react-native-action-sheet/ActionSheetProvider.js Unexpected token (5:19)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (5:19)
    at Parser.pp$4.raise 

ERROR in ./~/@exponent/react-native-action-sheet/ActionSheetProvider.js
Module parse failed: /home/user/prj/aws/node_modules/@exponent/react-native-action-sheet/ActionSheetProvider.js Unexpected token (22:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (22:6)
    at Parser.pp$4.raise ....

ERROR in ./~/@exponent/react-native-action-sheet/connectActionSheet.js
Module parse failed: /home/user/prj/wis/node_modules/@exponent/react-native-action-sheet/connectActionSheet.js Unexpected token (6:11)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (6:11)
    at Parser.pp$4.raise ...

webpack.config.js:

    loaders: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'react', 'react-native', 'babel-preset-stage-0', 'babel-preset-stage-1'],
          plugins: [
            ['syntax-class-properties', { spec: true }],
            ['transform-class-properties', { spec: true }],
          ],
        },
      },

[Android] Unsupported node type: transform

Hey,

I'm getting the following error when trying to open the action sheet:
image

Looks like checking for NativeModules.NativeAnimatedModule in this commit is not enough because we are using transform which it not supported yet in RN.

This commit from Aug 7, 2016 facebook/react-native@df05311 will introduce transform support but it will only be released with RN v0.33.0

I'm using a forked version that sets the useNativeDriver=false for now :(

Why no static API?

If using something like redux-saga or redux-observable then I would think of an action sheet as a type of side effect that should be handled outside of a component.

There's currently no way to present an action sheet outside of a component though, so one couldn't be shown from a saga.

I could look into it and maybe find some way to create a static API.

As an alternative or addition to this a more declarative component based API might also be nicer

Can use this component without expo?

Is there a way to import ActionSheet (without wrapping the app) directly and use it?
something simple as this:

import { ActionSheet } from '@expo/react-native-action-sheet';

class MyScreen extends React.Component {

  _openActionSheet = () => {
      // Same interface as https://facebook.github.io/react-native/docs/actionsheetios.html
      let options = ['Delete', 'Save', 'Cancel'];
      let destructiveButtonIndex = 0;
      let cancelButtonIndex = 2;
      ActionSheet.showActionSheetWithOptions(
        {
          options,
          cancelButtonIndex,
          destructiveButtonIndex,
        },
        buttonIndex => {
          // Do something here depending on the button index selected
        }
      );
  }

  render() {
      return (
        <View>
            {this._openActionSheet()}
        </View>
      );
  }
}

undefined is not an object (evaluating '_this._key = guid()')

Using the following versions

"@exponent/react-native-action-sheet": "git://github.com/exponentjs/react-native-action-sheet.git",
// or
"@exponent/react-native-action-sheet": "0.2.3",
"react": "15.3.1",
"react-native": "0.33.0"

When using the the component:

// other imports...
import ActionSheet from '@exponent/react-native-action-sheet';

export default class MyApp extends Component {
  static childContextTypes = {
    actionSheet: PropTypes.func,
  };

  getChildContext() {
    return {
      actionSheet: () => this._actionSheetRef,
    };
  }

  render() {
    return (
        <ActionSheet ref={component => this._actionSheetRef = component}>
          <TabBar/>
        </ActionSheet>
      );
  }
}

I get the error in the title:

simulator screen shot 15 sep 2016 15 36 49

Avoid showing 2 actionsheets

Is there a way to avoid 2 actionsheets?

If an user clicks faster in the button that call actionsheet, it will show 2 actionsheets,
is there a way to avoid this?

`yarn outdated` fails but `yarn` works!

Hey guys,
This is probably not an issue with this project, but thought you might want to know, and maybe encoutered it before,
So, running yarn in my react-native project worked well.
However, running yarn outdated fails with this error

Trace:
  Error: https://registry.yarnpkg.com/@exponent/react-native-action-sheet: Not found
      at Request.params.callback [as _callback] (/.nvm/versions/node/v4.5.0/lib/node_modules/yarn/lib-legacy/util/request-manager.js:306:18)
      at Request.self.callback (/.nvm/versions/node/v4.5.0/lib/node_modules/yarn/node_modules/request/request.js:186:22)
      at emitTwo (events.js:87:13)
      at Request.emit (events.js:172:7)
      at Request.<anonymous> (/.nvm/versions/node/v4.5.0/lib/node_modules/yarn/node_modules/request/request.js:1081:10)
      at emitOne (events.js:77:13)
      at Request.emit (events.js:169:7)
      at IncomingMessage.<anonymous> (/.nvm/versions/node/v4.5.0/lib/node_modules/yarn/node_modules/request/request.js:1001:12)
      at IncomingMessage.g (events.js:260:16)
      at emitNone (events.js:72:20)

const exports in index.js causing issues

Ran into an issue when running Jest tests(v 15.0).

SyntaxError: Identifier 'exports' has already been declared

Looks like my use of const exports in the index.js wasn't a good idea. Seemed to work fine in react-native, but Jest was failing due to the exports alias for node modules being redefined. My bad. I'll be submitting a pull request in a moment that goes back to the old syntax for index.js, but keeps the new provider/connect additions.

For the record Jest doesn't seem to fail on newer versions(was fine on 17), so this may not be much of a problem, but I could see it causing issues down the line.

68 Flow errors [master]

Hi,
I'm trying to use the flow script but it raises 68 errors.

[....more errors here...]

node_modules/react-native/Libraries/Image/ImageStylePropTypes.js:16
 16: var ReactPropTypes = require('ReactPropTypes');
                          ^^^^^^^^^^^^^^^^^^^^^^^^^ ReactPropTypes. Required module not found

node_modules/react-native/Libraries/Inspector/ElementProperties.js:15
 15: var PropTypes = require('ReactPropTypes');
                     ^^^^^^^^^^^^^^^^^^^^^^^^^ ReactPropTypes. Required module not found

node_modules/react-native/Libraries/LayoutAnimation/LayoutAnimation.js:14
 14: var PropTypes = require('ReactPropTypes');
                     ^^^^^^^^^^^^^^^^^^^^^^^^^ ReactPropTypes. Required module not found

node_modules/react-native/Libraries/Modal/Modal.js:15
 15: const PropTypes = require('ReactPropTypes');
                       ^^^^^^^^^^^^^^^^^^^^^^^^^ ReactPropTypes. Required module not found


... 18 more errors (only 50 out of 68 errors displayed)
To see all errors, re-run Flow with --show-all-errors

Looks like we should exclude some patterns in .flowconfig.

module no longer referenced in npm

Already opened same issue for fade-in:
For the past few hours, I've been having problems yarning my project:
Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "--save-dev" "eslint-config-rallycoding"
npm ERR! node v6.9.4
npm ERR! npm v3.10.10

npm ERR! Invalid name: "@exponent/react-native-action-sheet"

same problem with react-native-fade-in-image

Multiple destructiveButtonIndex for red color?

Hello,

I came across a situation where a user can delete the current item, or all items, and they both should be red, so destructiveButtonIndex = [0, 1];

However, that throws an error, as it expects a single integer value as opposed to an array of destructive indices.

How can both options be red?

Support >=RN25

import React from 'react';

instead of

import React from 'react-native';

#7

Example

Can you please add a sample app, I am getting one error after another.

Thanks

Invalid name

When I try to install npm install @expo/react-native-action-sheet I am getting this following error:

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "@expo/react-native-action-sheet"
npm ERR! node v6.9.5
npm ERR! npm v3.10.10

npm ERR! Invalid name: "@expo/react-native-action-sheet"
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:

Title?

Should we have the title for this component?

header not hidden when calling navigation.goBack()

so I have set route's navigationOptions.header = () => null, it displays correctly. However, when I call this.props.navigation.goBack, the header flashes for like 0.3s, then it's gone. The behaviour is not consistent through the entire navigation actions

Receiving warning (cases chrome breakpoint) Warning: PropTypes has been moved to a separate package. Accessing React.PropTypes is no longer supported and will be removed completely in React 16

Originating from ActionSheetProvider.js:6

Running with dependencies

  "dependencies": {
    "@expo/react-native-action-sheet": "^1.0.0",
    "@expo/samples": "^2.0.2",
    "expo": "^20.0.0",
    "react": "16.0.0-alpha.12",
    "react-native": "https://github.com/expo/react-native/archive/sdk-20.0.0.tar.gz",
    "react-native-sentry": "^0.21.2",
    "react-navigation": "^1.0.0-beta.12",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-persist": "^4.9.1"
  }

Please fix; this breaks my code every time the app reloads, unless I turn off breakpoints.

Thank you!

Error When importing

Version Expo: 23.0.4
my package.json dependencies :

    "@expo/react-native-action-sheet": "0.4.0",
    "@expo/vector-icons": "6.2.1",
    "date-fns": "2.0.0-alpha.7",
    "expo": "^23.0.4",
    "fela": "6.1.0",
    "fela-native": "5.0.14",
    "fela-plugin-extend": "6.0.2",
    "react": "16.0.0",
    "react-fela": "6.1.1",
    "react-native": "0.50.3",
    "react-native-animatable": "1.2.4",
    "react-navigation": "1.0.0-beta.21"

I tried to use action sheet and get an error when i import the package.
this is the piece of code :

// @flow
import React from "react";
import Expo from "expo";
import { AppRegistry } from "react-native";
import { Provider, ThemeProvider } from "react-fela";
import { Font } from "expo";
import { ActionSheetProvider } from "@expo/react-native-action-sheet";

import Root from "./root";
import renderer from "./fela";
import theme from "./theme";

class App extends React.Component {
  state = { fontLoaded: false };
  async componentDidMount() {
    await Font.loadAsync({
      "hk-grotesk-regular": require("./assets/fonts/HKGroteskRegular.ttf"),
      "hk-grotesk-bold": require("./assets/fonts/HKGroteskBold.ttf")
    });
    this.setState(() => ({ fontLoaded: true }));
  }
  render() {
    return this.state.fontLoaded ? (
      <Provider renderer={renderer}>
        <ThemeProvider theme={theme}>
          <Root />
        </ThemeProvider>
      </Provider>
    ) : null;
  }
}

export default App;

img_0326

If i can help or you need more info, let me know :)

Changes in ActionSheet.android.js were reverted

After this PR was merged e73314d#diff-3f3314f300451101b2c6e75447496621

The changes were (accidentally?) reverted by 3c2a61d#diff-3f3314f300451101b2c6e75447496621

npm hasn't been updated with the prop-types change yet so I tried using:
"@exponent/react-native-action-sheet": "github:expo/react-native-action-sheet",

Which does work for iOS but still fails for Android

Using the work around:
"@exponent/react-native-action-sheet": "github:xcarpentier/react-native-action-sheet",

until the change to master is reverted

Use without decorators?

It it possible to use this without decorators? There seems to be a lot of issue with RN 56's use of babel 7 and decorators.

Not working in RN 0.50.3

The @connectActionSheet before the class declaration, just as it is in docs, throws an error when trying to build. I assume this is because of some changes in RN 0.50.3? Any help/guidance would be awesome!

This is a brand new project, btw.
React 16.0.0
RN 0.50.3

Android Actionsheet not showing completely

I have an issue with Android. The Actionsheet is cut off at the end, the reason is that Dimensions.get('window').height seems to include the Status Bar and Soft Menu Bar height, I used a library to get the screen height without the extra https://github.com/jaysoo/react-native-extra-dimensions-android, I have a branch that allows to pass screenHeight as a prop: https://github.com/taskrabbit/react-native-action-sheet/tree/pass-screenheight-props

Any thought of how to resolve this without passing it?

Not sure if screenHeight is the best variable name either.

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.