0.1.3 • Published 5 years ago

react-native-modal-hooks v0.1.3

Weekly downloads
51
License
MIT
Repository
-
Last release
5 years ago

react-native-modal-hooks

Dialogs and prompts are one of the things that annoy me the most about React development. Showing and hiding parts of your views with visible and stuff like that seems excessive when all you really wanted was something closer to the native prompt function.

So react-native-modal-hooks does exactly that.

  • ✅ Android
  • ✅ iOS
  • ✅ Web (react-native-web)

demo-gif

Usage

Basics

// App.tsx / App.js
import { ProvideModal, useModal } from "react-native-modal-hooks";

function App() {
  return (
    <ProvideModal>
      <AwesomeScreen />
    </ProvideModal>
  );
}

// AwesomeScreen.tsx
import React from "react";
import { Button } from "react-native";

export function AwesomeScreen() {
  const { numberPrompt } = useModal();
  async function handleNumber() {
    const res = await numberPrompt();
    if (res) {
      // if res is undefined, the user didn't enter a value
      alert(`Output: ${res}`);
    }
  }

  return <Button title="Gief number" onPress={handleNumber} />;
}

Creating your own prompts

export function AwesomeScreen() {
  const { render } = useDialog();

  async function handlePress() {
    const value = await render(onClose => <StringPrompt onClose={onClose} />);
    // to use a dialog (with a close button) instead of a blank modal use `renderDialog`
    if (value) {
      alert(value);
    }
  }

  return (
    <View>
      <Button title="Open" onPress={handlePress} />
    </View>
  );
}

// Our custom prompt
function StringPrompt({ onClose }: { onClose: (value: string) => void }) {
  const [text, setText] = useState();
  return (
    <View>
      <TextInput onChangeText={text => setText(text)} />
      <Button onPress={() => onClose(text)} title="Save" />
    </View>
  );
}

Customize the dialog

Nobody should be forced to use any graphic design of mine. So you can provide your own renderDialog prop. You can look at the default dialog for inspiration.

function App() {
  return (
    <ProvideModal
      renderDialog={(onClose, children: dialogChildren) => (
        <MuchBetterDialog onClose={onClose}>{dialogChildren}</MuchBetterDialog>
      )}
    >
      <Navigation />
    </ProvideModal>
  );
}

More

  • Check out playground/App.tsx for more examples. Start the playground with yarn workspace playground start
  • If you feel the need to customize the numberPrompt or have any prompt requests, please open an issue.