├── .editorconfig
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── codeql.yml
│ ├── coverage.yml
│ ├── coveralls.yml
│ └── release-and-publish-to-npm.yml
├── .gitignore
├── .husky
├── .npmignore
├── commit-msg
└── pre-commit
├── .nvmrc
├── .prettierrc.js
├── .release-it.json
├── .yarnrc
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── babel.config.js
├── example
├── .bundle
│ └── config
├── .eslintrc.js
├── .gitignore
├── .prettierrc.js
├── .watchmanconfig
├── Gemfile
├── android
│ ├── app
│ │ ├── build.gradle
│ │ ├── debug.keystore
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── debug
│ │ │ └── AndroidManifest.xml
│ │ │ └── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ └── com
│ │ │ │ └── inputselectexample
│ │ │ │ ├── MainActivity.kt
│ │ │ │ └── MainApplication.kt
│ │ │ └── res
│ │ │ ├── drawable
│ │ │ └── rn_edit_text_material.xml
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── app.json
├── babel.config.js
├── index.js
├── ios
│ ├── .xcode.env
│ ├── InputSelectExample.xcodeproj
│ │ ├── project.pbxproj
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── InputSelectExample.xcscheme
│ ├── InputSelectExample.xcworkspace
│ │ └── contents.xcworkspacedata
│ ├── InputSelectExample
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.mm
│ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ ├── LaunchScreen.storyboard
│ │ ├── PrivacyInfo.xcprivacy
│ │ └── main.m
│ ├── InputSelectExampleTests
│ │ ├── Info.plist
│ │ └── InputSelectExampleTests.m
│ ├── Podfile
│ └── Podfile.lock
├── metro.config.js
├── package.json
├── src
│ ├── App.tsx
│ ├── WithClassComponent.tsx
│ └── data.ts
├── tsconfig.json
└── yarn.lock
├── jest-setup.ts
├── package.json
├── pull_request_template.md
├── scripts
└── bootstrap.js
├── src
├── __tests__
│ ├── empty-dropdown.test.tsx
│ ├── flat-list-dropdown.test.tsx
│ └── section-list-dropdown.test.tsx
├── asset
│ ├── arrow-down.png
│ └── check.png
├── components
│ ├── CheckBox
│ │ ├── checkbox.types.ts
│ │ └── index.tsx
│ ├── CustomModal
│ │ └── index.tsx
│ ├── Dropdown
│ │ ├── Dropdown.tsx
│ │ ├── DropdownListItem.tsx
│ │ └── DropdownSelectedItemsView.tsx
│ ├── Input
│ │ └── index.tsx
│ ├── List
│ │ ├── DropdownFlatList.tsx
│ │ └── DropdownSectionList.tsx
│ └── Others
│ │ └── index.tsx
├── constants
│ └── index.ts
├── hooks
│ ├── index.ts
│ ├── use-index-of-selected-item.ts
│ ├── use-modal.ts
│ ├── use-search.ts
│ ├── use-select-all.ts
│ └── use-selection-handler.ts
├── index.tsx
├── styles
│ ├── colors.ts
│ ├── input.ts
│ └── typography.ts
├── types
│ └── index.types.ts
└── utils
│ └── index.ts
├── tsconfig.build.json
├── tsconfig.json
└── yarn.lock
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "main" ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ "main" ]
20 | schedule:
21 | - cron: '28 13 * * 1'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'javascript', 'ruby' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Use only 'java' to analyze code written in Java, Kotlin or both
38 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
39 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
40 |
41 | steps:
42 | - name: Checkout repository
43 | uses: actions/checkout@v3
44 |
45 | # Initializes the CodeQL tools for scanning.
46 | - name: Initialize CodeQL
47 | uses: github/codeql-action/init@v2
48 | with:
49 | languages: ${{ matrix.language }}
50 | # If you wish to specify custom queries, you can do so here or in a config file.
51 | # By default, queries listed here will override any specified in a config file.
52 | # Prefix the list here with "+" to use these queries and those in the config file.
53 |
54 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
55 | # queries: security-extended,security-and-quality
56 |
57 |
58 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
59 | # If this step fails, then you should remove it and run the build manually (see below)
60 | - name: Autobuild
61 | uses: github/codeql-action/autobuild@v2
62 |
63 | # ℹ️ Command-line programs to run using the OS shell.
64 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
65 |
66 | # If the Autobuild fails above, remove it and uncomment the following three lines.
67 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
68 |
69 | # - run: |
70 | # echo "Run, Build Application using script"
71 | # ./location_of_script_within_repo/buildscript.sh
72 |
73 | - name: Perform CodeQL Analysis
74 | uses: github/codeql-action/analyze@v2
75 | with:
76 | category: "/language:${{matrix.language}}"
77 |
--------------------------------------------------------------------------------
/.github/workflows/coverage.yml:
--------------------------------------------------------------------------------
1 | name: 'coverage'
2 | on:
3 | pull_request:
4 | branches: ['main']
5 | jobs:
6 | coverage:
7 | permissions:
8 | checks: write
9 | pull-requests: write
10 | contents: write
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v3
14 | - uses: ArtiomTr/jest-coverage-report-action@v2
15 | with:
16 | package-manager: yarn
17 | test-script: npm test
18 |
--------------------------------------------------------------------------------
/.github/workflows/coveralls.yml:
--------------------------------------------------------------------------------
1 | on: ['push', 'pull_request', workflow_dispatch]
2 |
3 | name: Test Coveralls
4 |
5 | jobs:
6 | build:
7 | name: Build
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v4
11 |
12 | - name: Use Node.js 20.x
13 | uses: actions/setup-node@v3
14 | with:
15 | node-version: 20.x
16 |
17 | - name: Install npm dependencies
18 | run: npm install # switch to `npm ci` when Node.js 6 support is dropped
19 |
20 | - name: Run tests
21 | run: npm run test:coverage
22 |
23 | - name: Coveralls
24 | uses: coverallsapp/github-action@master
25 | with:
26 | github-token: ${{ secrets.GITHUB_TOKEN }}
27 | flag-name: ${{matrix.os}}-node-${{ matrix.node }}
28 | parallel: true
29 |
--------------------------------------------------------------------------------
/.github/workflows/release-and-publish-to-npm.yml:
--------------------------------------------------------------------------------
1 | name: 'Release & Publish to NPM'
2 |
3 | on: workflow_dispatch
4 |
5 | jobs:
6 | release:
7 | runs-on: ubuntu-latest
8 | permissions:
9 | packages: write
10 | contents: read
11 | steps:
12 | - name: Checkout repository
13 | uses: actions/checkout@v4
14 | with:
15 | token: ${{ secrets.PAT }}
16 | - name: Install the dependencies
17 | uses: borales/actions-yarn@v4
18 | with:
19 | cmd: install # will run `yarn install` command
20 | - name: Initialize Git user
21 | run: |
22 | git config --global user.email "azeezat94@gmail.com"
23 | git config --global user.name "Release Workflow"
24 | - name: Initialize npm config
25 | run: npm config set //registry.npmjs.org/:_authToken $NPM_TOKEN
26 | env:
27 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
28 | - name: Release
29 | run: npm run release --ci
30 | env:
31 | GITHUB_TOKEN: ${{ secrets.PAT }}
32 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
33 | - name: End Message
34 | run: echo "All done"
35 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .classpath
35 | .cxx
36 | .gradle
37 | .idea
38 | .project
39 | .settings
40 | local.properties
41 | android.iml
42 |
43 | # Cocoapods
44 | #
45 | example/ios/Pods
46 |
47 | # node.js
48 | #
49 | node_modules/
50 | npm-debug.log
51 | yarn-debug.log
52 | yarn-error.log
53 |
54 | # BUCK
55 | buck-out/
56 | \.buckd/
57 | android/app/libs
58 | android/keystores/debug.keystore
59 |
60 | # Expo
61 | .expo/*
62 |
63 | # generated by bob
64 | lib/
65 |
66 | # npm
67 | .npmrc
68 |
69 | # coverage
70 | coverage
--------------------------------------------------------------------------------
/.husky/.npmignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/.husky/commit-msg:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | yarn commitlint -E HUSKY_GIT_PARAMS
5 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | . "$(dirname "$0")/_/husky.sh"
3 |
4 | yarn lint && yarn test && yarn typescript
5 |
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | v20.9.0
2 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | bracketSpacing: true,
3 | jsxBracketSameLine: true,
4 | singleQuote: true,
5 | trailingComma: 'all',
6 | arrowParens: 'avoid',
7 | };
8 |
--------------------------------------------------------------------------------
/.release-it.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://unpkg.com/release-it@17/schema/release-it.json",
3 | "git": {
4 | "requireBranch": "main",
5 | "commitMessage": "chore: release v${version}",
6 | "tagName": "v${version}",
7 | "commit": true,
8 | "tag": true,
9 | "push": true
10 | },
11 | "github": {
12 | "release": true,
13 | "releaseName": "Release ${version}",
14 | "autoGenerate": true,
15 | "comments": {
16 | "submit": true,
17 | "issue": ":rocket: _This issue has been resolved in v${version}. See [${releaseName}](${releaseUrl}) for release notes._",
18 | "pr": ":rocket: _This pull request is included in v${version}. See [${releaseName}](${releaseUrl}) for release notes._"
19 | }
20 | },
21 | "hooks": {
22 | "before:init": ["git pull", "npm test"],
23 | "after:bump": "npx auto-changelog -p",
24 | "after:release": "echo Successfully released ${name} v${version} to ${repo.repository}."
25 | },
26 | "npm": {
27 | "publish": true
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/.yarnrc:
--------------------------------------------------------------------------------
1 | # Override Yarn command so we can automatically setup the repo on running `yarn`
2 |
3 | yarn-path "scripts/bootstrap.js"
4 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | azeezat94@gmail.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn
11 | ```
12 |
13 | > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development.
14 |
15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app.
16 |
17 | To setup project by installing all dependencies and pods:
18 |
19 | `yarn bootstrap`
20 |
21 |
22 | To start the packager:
23 |
24 | ```sh
25 | yarn start
26 | ```
27 |
28 | To run the example app on Android:
29 |
30 | ```sh
31 | yarn android
32 | ```
33 |
34 | To run the example app on iOS:
35 |
36 | ```sh
37 | yarn ios
38 | ```
39 |
40 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
41 |
42 | ```sh
43 | yarn typescript
44 | yarn lint
45 | ```
46 |
47 | To fix formatting errors, run the following:
48 |
49 | ```sh
50 | yarn lint --fix
51 | ```
52 |
53 | Remember to add tests for your change if possible. Run the unit tests by:
54 |
55 | ```sh
56 | yarn test
57 | ```
58 |
59 | ### Commit message convention
60 |
61 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
62 |
63 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
64 | - `feat`: new features, e.g. add new method to the module.
65 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
66 | - `docs`: changes into documentation, e.g. add usage example for the module..
67 | - `test`: adding or updating tests, e.g. add integration tests using detox.
68 | - `chore`: tooling changes, e.g. change CI config.
69 |
70 | Our pre-commit hooks verify that your commit message matches this format when committing.
71 |
72 | ### Linting and tests
73 |
74 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
75 |
76 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
77 |
78 | Our pre-commit hooks verify that the linter and tests pass when committing.
79 |
80 | ### Publishing to npm
81 |
82 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
83 |
84 | To publish new versions, run the following:
85 |
86 | ```sh
87 | yarn release
88 | ```
89 |
90 | ### Scripts
91 |
92 | The `package.json` file contains various scripts for common tasks:
93 |
94 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
95 | - `yarn typescript`: type-check files with TypeScript.
96 | - `yarn lint`: lint files with ESLint.
97 | - `yarn test`: run unit tests with Jest.
98 | - `yarn example start`: start the Metro server for the example app.
99 | - `yarn example android`: run the example app on Android.
100 | - `yarn example ios`: run the example app on iOS.
101 |
102 | ### Sending a pull request
103 |
104 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
105 |
106 | When you're sending a pull request:
107 |
108 | - Prefer small pull requests focused on one change.
109 | - Verify that linters and tests are passing.
110 | - Review the documentation to make sure it looks good.
111 | - Follow the pull request template when opening a pull request.
112 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
113 |
114 | ## Code of Conduct
115 |
116 | ### Our Pledge
117 |
118 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
119 |
120 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
121 |
122 | ### Our Standards
123 |
124 | Examples of behavior that contributes to a positive environment for our community include:
125 |
126 | - Demonstrating empathy and kindness toward other people
127 | - Being respectful of differing opinions, viewpoints, and experiences
128 | - Giving and gracefully accepting constructive feedback
129 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
130 | - Focusing on what is best not just for us as individuals, but for the overall community
131 |
132 | Examples of unacceptable behavior include:
133 |
134 | - The use of sexualized language or imagery, and sexual attention or
135 | advances of any kind
136 | - Trolling, insulting or derogatory comments, and personal or political attacks
137 | - Public or private harassment
138 | - Publishing others' private information, such as a physical or email
139 | address, without their explicit permission
140 | - Other conduct which could reasonably be considered inappropriate in a
141 | professional setting
142 |
143 | ### Enforcement Responsibilities
144 |
145 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
146 |
147 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
148 |
149 | ### Scope
150 |
151 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
152 |
153 | ### Enforcement
154 |
155 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
156 |
157 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
158 |
159 | ### Enforcement Guidelines
160 |
161 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
162 |
163 | #### 1. Correction
164 |
165 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
166 |
167 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
168 |
169 | #### 2. Warning
170 |
171 | **Community Impact**: A violation through a single incident or series of actions.
172 |
173 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
174 |
175 | #### 3. Temporary Ban
176 |
177 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
178 |
179 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
180 |
181 | #### 4. Permanent Ban
182 |
183 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
184 |
185 | **Consequence**: A permanent ban from any sort of public interaction within the community.
186 |
187 | ### Attribution
188 |
189 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
190 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
191 |
192 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
193 |
194 | [homepage]: https://www.contributor-covenant.org
195 |
196 | For answers to common questions about this code of conduct, see the FAQ at
197 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
198 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Azeezat Raheem
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Use this section to tell people about which versions of your project are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ---------- | ------------------ |
10 | | 2.1.x | :white_check_mark: |
11 | | < 2.1.x | :x: |
12 |
13 | ## Reporting a Vulnerability
14 |
15 | Use this section to tell people how to report a vulnerability.
16 |
17 | To report a vlnerability, use the **Report a security vulnerability** template on github
18 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | overrides: [
4 | {
5 | plugins: [
6 | [
7 | '@babel/plugin-transform-private-methods',
8 | {
9 | loose: true,
10 | },
11 | ],
12 | ],
13 | },
14 | ],
15 | };
16 |
--------------------------------------------------------------------------------
/example/.bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/example/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: ['@react-native'],
4 | };
5 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | **/.xcode.env.local
24 |
25 | # Android/IntelliJ
26 | #
27 | build/
28 | .idea
29 | .gradle
30 | local.properties
31 | *.iml
32 | *.hprof
33 | .cxx/
34 | *.keystore
35 | !debug.keystore
36 |
37 | # node.js
38 | #
39 | node_modules/
40 | npm-debug.log
41 | yarn-error.log
42 |
43 | # fastlane
44 | #
45 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
46 | # screenshots whenever they are needed.
47 | # For more information about the recommended setup visit:
48 | # https://docs.fastlane.tools/best-practices/source-control/
49 |
50 | **/fastlane/report.xml
51 | **/fastlane/Preview.html
52 | **/fastlane/screenshots
53 | **/fastlane/test_output
54 |
55 | # Bundle artifact
56 | *.jsbundle
57 |
58 | # Ruby / CocoaPods
59 | **/Pods/
60 | /vendor/bundle/
61 |
62 | # Temporary files created by Metro to check the health of the file watcher
63 | .metro-health-check*
64 |
65 | # testing
66 | /coverage
67 |
68 | # Yarn
69 | .yarn/*
70 | !.yarn/patches
71 | !.yarn/plugins
72 | !.yarn/releases
73 | !.yarn/sdks
74 | !.yarn/versions
75 |
--------------------------------------------------------------------------------
/example/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | arrowParens: 'avoid',
3 | bracketSameLine: true,
4 | bracketSpacing: false,
5 | singleQuote: true,
6 | trailingComma: 'all',
7 | };
8 |
--------------------------------------------------------------------------------
/example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/example/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby ">= 2.6.10"
5 |
6 | # Cocoapods 1.15 introduced a bug which break the build. We will remove the upper
7 | # bound in the template on Cocoapods with next React Native release.
8 | gem 'cocoapods', '>= 1.13', '< 1.15'
9 | gem 'activesupport', '>= 6.1.7.5', '< 7.1.0'
10 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 | apply plugin: "org.jetbrains.kotlin.android"
3 | apply plugin: "com.facebook.react"
4 |
5 | /**
6 | * This is the configuration block to customize your React Native Android app.
7 | * By default you don't need to apply any configuration, just uncomment the lines you need.
8 | */
9 | react {
10 | /* Folders */
11 | // The root of your project, i.e. where "package.json" lives. Default is '..'
12 | // root = file("../")
13 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native
14 | // reactNativeDir = file("../node_modules/react-native")
15 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
16 | // codegenDir = file("../node_modules/@react-native/codegen")
17 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
18 | // cliFile = file("../node_modules/react-native/cli.js")
19 |
20 | /* Variants */
21 | // The list of variants to that are debuggable. For those we're going to
22 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'.
23 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
24 | // debuggableVariants = ["liteDebug", "prodDebug"]
25 |
26 | /* Bundling */
27 | // A list containing the node command and its flags. Default is just 'node'.
28 | // nodeExecutableAndArgs = ["node"]
29 | //
30 | // The command to run when bundling. By default is 'bundle'
31 | // bundleCommand = "ram-bundle"
32 | //
33 | // The path to the CLI configuration file. Default is empty.
34 | // bundleConfig = file(../rn-cli.config.js)
35 | //
36 | // The name of the generated asset file containing your JS bundle
37 | // bundleAssetName = "MyApplication.android.bundle"
38 | //
39 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
40 | // entryFile = file("../js/MyApplication.android.js")
41 | //
42 | // A list of extra flags to pass to the 'bundle' commands.
43 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
44 | // extraPackagerArgs = []
45 |
46 | /* Hermes Commands */
47 | // The hermes compiler command to run. By default it is 'hermesc'
48 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
49 | //
50 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
51 | // hermesFlags = ["-O", "-output-source-map"]
52 | }
53 |
54 | /**
55 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
56 | */
57 | def enableProguardInReleaseBuilds = false
58 |
59 | /**
60 | * The preferred build flavor of JavaScriptCore (JSC)
61 | *
62 | * For example, to use the international variant, you can use:
63 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
64 | *
65 | * The international variant includes ICU i18n library and necessary data
66 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
67 | * give correct results when using with locales other than en-US. Note that
68 | * this variant is about 6MiB larger per architecture than default.
69 | */
70 | def jscFlavor = 'org.webkit:android-jsc:+'
71 |
72 | android {
73 | ndkVersion rootProject.ext.ndkVersion
74 | buildToolsVersion rootProject.ext.buildToolsVersion
75 | compileSdk rootProject.ext.compileSdkVersion
76 |
77 | namespace "com.inputselectexample"
78 | defaultConfig {
79 | applicationId "com.inputselectexample"
80 | minSdkVersion rootProject.ext.minSdkVersion
81 | targetSdkVersion rootProject.ext.targetSdkVersion
82 | versionCode 1
83 | versionName "1.0"
84 | }
85 | signingConfigs {
86 | debug {
87 | storeFile file('debug.keystore')
88 | storePassword 'android'
89 | keyAlias 'androiddebugkey'
90 | keyPassword 'android'
91 | }
92 | }
93 | buildTypes {
94 | debug {
95 | signingConfig signingConfigs.debug
96 | }
97 | release {
98 | // Caution! In production, you need to generate your own keystore file.
99 | // see https://reactnative.dev/docs/signed-apk-android.
100 | signingConfig signingConfigs.debug
101 | minifyEnabled enableProguardInReleaseBuilds
102 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
103 | }
104 | }
105 | }
106 |
107 | dependencies {
108 | // The version of react-native is set by the React Native Gradle Plugin
109 | implementation("com.facebook.react:react-android")
110 |
111 | if (hermesEnabled.toBoolean()) {
112 | implementation("com.facebook.react:hermes-android")
113 | } else {
114 | implementation jscFlavor
115 | }
116 | }
117 |
118 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
119 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/debug.keystore
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/inputselectexample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.inputselectexample
2 |
3 | import com.facebook.react.ReactActivity
4 | import com.facebook.react.ReactActivityDelegate
5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
6 | import com.facebook.react.defaults.DefaultReactActivityDelegate
7 |
8 | class MainActivity : ReactActivity() {
9 |
10 | /**
11 | * Returns the name of the main component registered from JavaScript. This is used to schedule
12 | * rendering of the component.
13 | */
14 | override fun getMainComponentName(): String = "InputSelectExample"
15 |
16 | /**
17 | * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
18 | * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
19 | */
20 | override fun createReactActivityDelegate(): ReactActivityDelegate =
21 | DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
22 | }
23 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/inputselectexample/MainApplication.kt:
--------------------------------------------------------------------------------
1 | package com.inputselectexample
2 |
3 | import android.app.Application
4 | import com.facebook.react.PackageList
5 | import com.facebook.react.ReactApplication
6 | import com.facebook.react.ReactHost
7 | import com.facebook.react.ReactNativeHost
8 | import com.facebook.react.ReactPackage
9 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
10 | import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
11 | import com.facebook.react.defaults.DefaultReactNativeHost
12 | import com.facebook.soloader.SoLoader
13 |
14 | class MainApplication : Application(), ReactApplication {
15 |
16 | override val reactNativeHost: ReactNativeHost =
17 | object : DefaultReactNativeHost(this) {
18 | override fun getPackages(): List =
19 | PackageList(this).packages.apply {
20 | // Packages that cannot be autolinked yet can be added manually here, for example:
21 | // add(MyReactNativePackage())
22 | }
23 |
24 | override fun getJSMainModuleName(): String = "index"
25 |
26 | override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
27 |
28 | override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
29 | override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
30 | }
31 |
32 | override val reactHost: ReactHost
33 | get() = getDefaultReactHost(applicationContext, reactNativeHost)
34 |
35 | override fun onCreate() {
36 | super.onCreate()
37 | SoLoader.init(this, false)
38 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
39 | // If you opted-in for the New Architecture, we load the native entry point for this app.
40 | load()
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
22 |
23 |
24 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | InputSelectExample
3 |
4 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/example/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | buildToolsVersion = "34.0.0"
4 | minSdkVersion = 23
5 | compileSdkVersion = 34
6 | targetSdkVersion = 34
7 | ndkVersion = "26.1.10909125"
8 | kotlinVersion = "1.9.22"
9 | }
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | dependencies {
15 | classpath("com.android.tools.build:gradle")
16 | classpath("com.facebook.react:react-native-gradle-plugin")
17 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
18 | }
19 | }
20 |
21 | apply plugin: "com.facebook.react.rootproject"
22 |
--------------------------------------------------------------------------------
/example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 | # Automatically convert third-party libraries to use AndroidX
25 | android.enableJetifier=true
26 |
27 | # Use this property to specify which architecture you want to build.
28 | # You can also override it from the CLI using
29 | # ./gradlew -PreactNativeArchitectures=x86_64
30 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
31 |
32 | # Use this property to enable support to the new architecture.
33 | # This will allow you to use TurboModules and the Fabric render in
34 | # your application. You should enable this flag either if you want
35 | # to write custom TurboModules/Fabric components OR use libraries that
36 | # are providing them.
37 | newArchEnabled=false
38 |
39 | # Use this property to enable or disable the Hermes JS engine.
40 | # If set to false, you will be using JSC instead.
41 | hermesEnabled=true
42 |
43 | org.gradle.java.home=/Library/Java/JavaVirtualMachines/zulu-17.jdk/Contents/Home
44 |
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo. 1>&2
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
48 | echo. 1>&2
49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
50 | echo location of your Java installation. 1>&2
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo. 1>&2
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
62 | echo. 1>&2
63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
64 | echo location of your Java installation. 1>&2
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'InputSelectExample'
2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
3 | include ':app'
4 | includeBuild('../node_modules/@react-native/gradle-plugin')
5 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "InputSelectExample",
3 | "displayName": "Input Select Example"
4 | }
5 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = {
5 | presets: ['module:metro-react-native-babel-preset'],
6 | plugins: [
7 | [
8 | 'module-resolver',
9 | {
10 | extensions: ['.tsx', '.ts', '.js', '.json'],
11 | alias: [
12 | {
13 | [pak.name]: path.join(__dirname, '..', pak.source),
14 | },
15 | ],
16 | },
17 | ],
18 | ],
19 | overrides: [
20 | {
21 | plugins: [
22 | [
23 | '@babel/plugin-transform-private-methods',
24 | {
25 | loose: true,
26 | },
27 | ],
28 | ],
29 | },
30 | ],
31 | };
32 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import {AppRegistry} from 'react-native';
2 | import App from './src/App';
3 | import {name as appName} from './app.json';
4 |
5 | AppRegistry.registerComponent(appName, () => App);
6 |
--------------------------------------------------------------------------------
/example/ios/.xcode.env:
--------------------------------------------------------------------------------
1 | # This `.xcode.env` file is versioned and is used to source the environment
2 | # used when running script phases inside Xcode.
3 | # To customize your local environment, you can create an `.xcode.env.local`
4 | # file that is not versioned.
5 |
6 | # NODE_BINARY variable contains the PATH to the node executable.
7 | #
8 | # Customize the NODE_BINARY variable here.
9 | # For example, to use nvm with brew, add the following line
10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use
11 | export NODE_BINARY=$(command -v node)
12 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample.xcodeproj/xcshareddata/xcschemes/InputSelectExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | @interface AppDelegate : RCTAppDelegate
5 |
6 | @end
7 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/AppDelegate.mm:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 |
5 | @implementation AppDelegate
6 |
7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
8 | {
9 | self.moduleName = @"InputSelectExample";
10 | // You can add your custom initial props in the dictionary below.
11 | // They will be passed down to the ViewController used by React Native.
12 | self.initialProps = @{};
13 |
14 | return [super application:application didFinishLaunchingWithOptions:launchOptions];
15 | }
16 |
17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
18 | {
19 | return [self bundleURL];
20 | }
21 |
22 | - (NSURL *)bundleURL
23 | {
24 | #if DEBUG
25 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
26 | #else
27 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
28 | #endif
29 | }
30 |
31 | @end
32 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ios-marketing",
45 | "scale" : "1x",
46 | "size" : "1024x1024"
47 | }
48 | ],
49 | "info" : {
50 | "author" : "xcode",
51 | "version" : 1
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | InputSelectExample
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | $(CURRENT_PROJECT_VERSION)
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 |
30 | NSAllowsArbitraryLoads
31 |
32 | NSAllowsLocalNetworking
33 |
34 |
35 | NSLocationWhenInUseUsageDescription
36 |
37 | UILaunchStoryboardName
38 | LaunchScreen
39 | UIRequiredDeviceCapabilities
40 |
41 | arm64
42 |
43 | UISupportedInterfaceOrientations
44 |
45 | UIInterfaceOrientationPortrait
46 | UIInterfaceOrientationLandscapeLeft
47 | UIInterfaceOrientationLandscapeRight
48 |
49 | UIViewControllerBasedStatusBarAppearance
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
24 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/PrivacyInfo.xcprivacy:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | NSPrivacyAccessedAPITypes
6 |
7 |
8 | NSPrivacyAccessedAPIType
9 | NSPrivacyAccessedAPICategoryFileTimestamp
10 | NSPrivacyAccessedAPITypeReasons
11 |
12 | C617.1
13 |
14 |
15 |
16 | NSPrivacyAccessedAPIType
17 | NSPrivacyAccessedAPICategoryUserDefaults
18 | NSPrivacyAccessedAPITypeReasons
19 |
20 | CA92.1
21 |
22 |
23 |
24 | NSPrivacyAccessedAPIType
25 | NSPrivacyAccessedAPICategorySystemBootTime
26 | NSPrivacyAccessedAPITypeReasons
27 |
28 | 35F9.1
29 |
30 |
31 |
32 | NSPrivacyCollectedDataTypes
33 |
34 | NSPrivacyTracking
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExample/main.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "AppDelegate.h"
4 |
5 | int main(int argc, char *argv[])
6 | {
7 | @autoreleasepool {
8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExampleTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/example/ios/InputSelectExampleTests/InputSelectExampleTests.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import
6 |
7 | #define TIMEOUT_SECONDS 600
8 | #define TEXT_TO_LOOK_FOR @"Welcome to React"
9 |
10 | @interface InputSelectExampleTests : XCTestCase
11 |
12 | @end
13 |
14 | @implementation InputSelectExampleTests
15 |
16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
17 | {
18 | if (test(view)) {
19 | return YES;
20 | }
21 | for (UIView *subview in [view subviews]) {
22 | if ([self findSubviewInView:subview matching:test]) {
23 | return YES;
24 | }
25 | }
26 | return NO;
27 | }
28 |
29 | - (void)testRendersWelcomeScreen
30 | {
31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33 | BOOL foundElement = NO;
34 |
35 | __block NSString *redboxError = nil;
36 | #ifdef DEBUG
37 | RCTSetLogFunction(
38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
39 | if (level >= RCTLogLevelError) {
40 | redboxError = message;
41 | }
42 | });
43 | #endif
44 |
45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
48 |
49 | foundElement = [self findSubviewInView:vc.view
50 | matching:^BOOL(UIView *view) {
51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
52 | return YES;
53 | }
54 | return NO;
55 | }];
56 | }
57 |
58 | #ifdef DEBUG
59 | RCTSetLogFunction(RCTDefaultLogFunction);
60 | #endif
61 |
62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/example/ios/Podfile:
--------------------------------------------------------------------------------
1 | # Resolve react_native_pods.rb with node to allow for hoisting
2 | require Pod::Executable.execute_command('node', ['-p',
3 | 'require.resolve(
4 | "react-native/scripts/react_native_pods.rb",
5 | {paths: [process.argv[1]]},
6 | )', __dir__]).strip
7 |
8 | platform :ios, min_ios_version_supported
9 | prepare_react_native_project!
10 |
11 | linkage = ENV['USE_FRAMEWORKS']
12 | if linkage != nil
13 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
14 | use_frameworks! :linkage => linkage.to_sym
15 | end
16 |
17 | target 'InputSelectExample' do
18 | config = use_native_modules!
19 |
20 | use_react_native!(
21 | :path => config[:reactNativePath],
22 | # An absolute path to your application root.
23 | :app_path => "#{Pod::Config.instance.installation_root}/.."
24 | )
25 |
26 | target 'InputSelectExampleTests' do
27 | inherit! :complete
28 | # Pods for testing
29 | end
30 |
31 | post_install do |installer|
32 | # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
33 | react_native_post_install(
34 | installer,
35 | config[:reactNativePath],
36 | :mac_catalyst_enabled => false,
37 | # :ccache_enabled => true
38 | )
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
2 | const path = require('path');
3 | const blacklist = require('metro-config/src/defaults/exclusionList');
4 | const escape = require('escape-string-regexp');
5 | const pak = require('../package.json');
6 | /**
7 | * Metro configuration
8 | * https://reactnative.dev/docs/metro
9 | *
10 | * @type {import('metro-config').MetroConfig}
11 | */
12 |
13 | const defaultConfig = getDefaultConfig(__dirname);
14 |
15 | const root = path.resolve(__dirname, '..');
16 |
17 | const modules = Object.keys({
18 | ...pak.peerDependencies,
19 | });
20 |
21 | const config = {
22 | projectRoot: __dirname,
23 | watchFolders: [root],
24 | resolver: {
25 | // We need to make sure that only one version is loaded for peerDependencies
26 | // So we blacklist them at the root, and alias them to the versions in example's node_modules
27 | blacklistRE: blacklist(
28 | modules.map(
29 | m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`),
30 | ),
31 | ),
32 |
33 | extraNodeModules: modules.reduce((acc, name) => {
34 | acc[name] = path.join(__dirname, 'node_modules', name);
35 | return acc;
36 | }, {}),
37 | },
38 | transformer: {
39 | getTransformOptions: async () => ({
40 | transform: {
41 | experimentalImportSupport: false,
42 | inlineRequires: true,
43 | },
44 | }),
45 | },
46 | };
47 |
48 | module.exports = mergeConfig(defaultConfig, config);
49 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "input-select-example",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "android": "react-native run-android",
7 | "ios": "react-native run-ios",
8 | "lint": "eslint .",
9 | "start": "react-native start",
10 | "test": "jest",
11 | "clean": "react-native start --reset-cache"
12 | },
13 | "dependencies": {
14 | "react": "^18.3.1",
15 | "react-native": "^0.74.1"
16 | },
17 | "devDependencies": {
18 | "@babel/core": "^7.20.0",
19 | "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
20 | "@babel/plugin-transform-private-methods": "^7.24.6",
21 | "@babel/preset-env": "^7.20.0",
22 | "@babel/runtime": "^7.20.0",
23 | "@react-native/babel-preset": "0.74.83",
24 | "@react-native/eslint-config": "0.74.83",
25 | "@react-native/metro-config": "0.74.83",
26 | "@react-native/typescript-config": "0.74.83",
27 | "@types/react": "^18.2.6",
28 | "@types/react-test-renderer": "^18.0.0",
29 | "babel-jest": "^29.6.3",
30 | "babel-plugin-module-resolver": "^5.0.2",
31 | "eslint": "^8.19.0",
32 | "jest": "^29.6.3",
33 | "metro-react-native-babel-preset": "^0.77.0",
34 | "prettier": "2.8.8",
35 | "react-test-renderer": "^18.3.0",
36 | "typescript": "5.0.4"
37 | },
38 | "engines": {
39 | "node": ">=18"
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react-native/no-inline-styles */
2 | import React, {useEffect, useRef, useState} from 'react';
3 | import {
4 | SafeAreaView,
5 | ScrollView,
6 | View,
7 | StyleSheet,
8 | Text,
9 | Button,
10 | Alert,
11 | Image,
12 | Pressable,
13 | TouchableHighlight,
14 | } from 'react-native';
15 | import DropdownSelect from 'react-native-input-select';
16 | import {countries} from './data';
17 | import {DropdownSelectHandle} from '../../src/types/index.types';
18 |
19 | export default function App() {
20 | const [user, setUser] = useState('');
21 | const [country, setCountry] = useState('');
22 | const [gender, setGender] = useState();
23 | const [currency, setCurrency] = useState([]);
24 | const [meals, setMeals] = useState([]);
25 | const [item, setItem] = useState('');
26 | const [menu, setMenu] = useState([]);
27 | const [searchTerm, setSearchTerm] = useState('');
28 | const [ingredients, setIngredients] = useState([]);
29 | const [ingredientOptions, setIngredientOptions] = useState([
30 | {label: 0, value: 0},
31 | {label: 1, value: false},
32 | {label: 2, value: 2, disabled: true},
33 | ]);
34 | useEffect(() => {
35 | setCurrency(['NGN']);
36 | setMenu(['F']);
37 | }, []);
38 |
39 | const logMovies = async () => {
40 | console.log('You can make an API call when the modal opens.');
41 | };
42 |
43 | const dropdownRef = useRef(null);
44 |
45 | return (
46 |
47 |
48 |
49 | {}}
55 | />
56 |
57 | setCurrency(itemValue)}
69 | isMultiple
70 | isSearchable
71 | primaryColor={'deepskyblue'}
72 | />
73 |
74 |
81 |
87 |
88 | Male
89 |
90 | ),
91 | id: 0,
92 | },
93 | {
94 | name: (
95 |
96 |
102 |
103 | Female
104 |
105 | ),
106 | id: 1,
107 | },
108 | ]}
109 | optionLabel={'name'}
110 | optionValue={'id'}
111 | selectedValue={gender}
112 | onValueChange={(itemValue: any) => setGender(itemValue)}
113 | dropdownErrorStyle={{
114 | borderColor: 'red',
115 | borderWidth: 2,
116 | borderStyle: 'solid',
117 | }}
118 | dropdownErrorTextStyle={{color: 'red', fontWeight: '500'}}
119 | error={gender === undefined ? 'Gender is required' : ''}
120 | modalControls={{
121 | modalProps: {
122 | onShow: () => logMovies(),
123 | onDismiss: () => console.log('modal was dismissed'),
124 | },
125 | }}
126 | />
127 |
128 | setUser(itemValue)}
137 | isSearchable
138 | primaryColor={'purple'}
139 | dropdownStyle={{
140 | borderWidth: 0, // To remove border, set borderWidth to 0
141 | }}
142 | dropdownIcon={
143 | user && (
144 |
145 |
146 |
147 | )
148 | }
149 | dropdownIconStyle={user ? {top: 20, right: 15} : {}}
150 | searchControls={{
151 | textInputStyle: {
152 | color: 'blue',
153 | fontWeight: '500',
154 | minHeight: 10,
155 | paddingVertical: 10,
156 | paddingHorizontal: 5,
157 | width: '70%',
158 | textAlign: 'center',
159 | backgroundColor: 'pink',
160 | },
161 | textInputContainerStyle: {
162 | flex: 1,
163 | justifyContent: 'center',
164 | alignItems: 'center',
165 | },
166 | textInputProps: {
167 | placeholder: 'Search anything here',
168 | placeholderTextColor: 'white',
169 | },
170 | }}
171 | />
172 |
173 | {
187 | meals.length === 2 && console.log('You can only select 2 meals');
188 |
189 | setMeals(itemValue);
190 | }}
191 | dropdownStyle={{
192 | backgroundColor: 'yellow',
193 | paddingVertical: 5,
194 | paddingHorizontal: 5,
195 | minHeight: 40,
196 | borderColor: 'green',
197 | }}
198 | dropdownIconStyle={{top: 15, right: 10}}
199 | dropdownContainerStyle={{marginBottom: 40}}
200 | dropdownHelperTextStyle={{
201 | color: 'green',
202 | fontWeight: '900',
203 | }}
204 | modalControls={{
205 | modalBackgroundStyle: {
206 | backgroundColor: 'rgba(196, 198, 246, 0.5)',
207 | },
208 | }}
209 | helperText="Some items in this list are disabled"
210 | isMultiple
211 | checkboxControls={{
212 | checkboxStyle: {
213 | backgroundColor: 'green',
214 | borderRadius: 30,
215 | borderColor: 'green',
216 | },
217 | checkboxLabelStyle: {color: 'green', fontSize: 20},
218 | checkboxUnselectedColor: 'black',
219 | checkboxComponent: ,
220 | }}
221 | listControls={{
222 | hideSelectAll: true,
223 | }}
224 | />
225 |
226 | setItem(itemValue)}
235 | placeholderStyle={{
236 | color: 'purple',
237 | fontSize: 15,
238 | fontWeight: '500',
239 | }}
240 | labelStyle={{color: 'teal', fontSize: 15, fontWeight: '500'}}
241 | dropdownHelperTextStyle={{
242 | color: 'green',
243 | fontWeight: '900',
244 | }}
245 | modalControls={{
246 | modalBackgroundStyle: {
247 | backgroundColor: 'rgba(196, 198, 246, 0.5)',
248 | },
249 | }}
250 | helperText="The placeholder has been styled"
251 | checkboxControls={{
252 | checkboxSize: 15,
253 | checkboxStyle: {
254 | backgroundColor: 'purple',
255 | borderRadius: 30, // To get a circle - add the checkboxSize and the padding size
256 | padding: 5,
257 | borderColor: 'red',
258 | },
259 | checkboxLabelStyle: {color: 'red', fontSize: 20},
260 | checkboxComponent: ,
261 | }}
262 | selectedItemStyle={{
263 | color: 'hotpink',
264 | fontWeight: '900',
265 | }}
266 | />
267 | dropdownRef.current?.open()}
269 | style={{
270 | alignSelf: 'flex-start',
271 | backgroundColor: 'green',
272 | marginBottom: 20,
273 | padding: 3,
274 | }}>
275 |
276 | Open the dropdown below by pressing this component
277 |
278 |
279 | setCountry(itemValue)}
287 | isMultiple
288 | isSearchable
289 | primaryColor={'orange'}
290 | dropdownStyle={{
291 | borderWidth: 0, // To remove border, set borderWidth to 0
292 | }}
293 | dropdownIcon={
294 |
300 | }
301 | dropdownIconStyle={{top: 20, right: 20}}
302 | listHeaderComponent={
303 |
304 |
305 | 💡 You can add any component to the top of this list
306 |
307 |
308 |
323 |
324 | }
325 | listFooterComponent={
326 |
327 |
328 | You can add any component to the bottom of this list
329 |
330 |
331 | }
332 | modalControls={{
333 | modalOptionsContainerStyle: {
334 | padding: 10,
335 | backgroundColor: 'cyan',
336 | },
337 | modalProps: {
338 | supportedOrientations: [
339 | 'portrait',
340 | 'portrait-upside-down',
341 | 'landscape',
342 | 'landscape-left',
343 | 'landscape-right',
344 | ],
345 | transparent: false,
346 | onShow: () => logMovies(),
347 | onDismiss: () => console.log('modal was dismissed'),
348 | },
349 | }}
350 | listComponentStyles={{
351 | listEmptyComponentStyle: {
352 | color: 'red',
353 | },
354 | itemSeparatorStyle: {
355 | opacity: 0,
356 | borderColor: 'white',
357 | borderWidth: 2,
358 | backgroundColor: 'cyan',
359 | },
360 | sectionHeaderStyle: {
361 | padding: 10,
362 | backgroundColor: 'cyan',
363 | },
364 | }}
365 | listControls={{
366 | selectAllText: 'Select all that applies',
367 | unselectAllText: 'Remove everything',
368 | selectAllCallback: () => Alert.alert('You selected everything'),
369 | unselectAllCallback: () => Alert.alert('You removed everything'),
370 | emptyListMessage: 'No record found',
371 | }}
372 | ref={dropdownRef}
373 | />
374 |
375 | {/* Section list */}
376 | setMenu(itemValue)}
406 | isMultiple
407 | isSearchable
408 | primaryColor={'#1c2d6b'}
409 | checkboxControls={{
410 | checkboxDisabledStyle: {
411 | borderColor: 'red',
412 | backgroundColor: 'red',
413 | },
414 | }}
415 | listComponentStyles={{
416 | sectionHeaderStyle: {
417 | paddingVertical: 6,
418 | paddingHorizontal: 12,
419 | backgroundColor: '#1c2d6b',
420 | color: 'white',
421 | borderRadius: 6,
422 | overflow: 'hidden',
423 | },
424 | }}
425 | multipleSelectedItemStyle={{
426 | borderRadius: 0,
427 | backgroundColor: 'hotpink',
428 | color: 'black',
429 | }}
430 | />
431 |
432 | {/* Add search item to list */}
433 | setIngredients(itemValue)}
439 | isMultiple
440 | isSearchable
441 | listEmptyComponent={
442 |
449 |
451 | setIngredientOptions([
452 | ...ingredientOptions,
453 | {label: searchTerm, value: searchTerm},
454 | ])
455 | }
456 | style={{
457 | backgroundColor: 'blue',
458 | borderRadius: 5,
459 | width: 120,
460 | padding: 5,
461 | }}>
462 |
463 | Add ingredient
464 |
465 |
466 |
467 | }
468 | searchControls={{searchCallback: value => setSearchTerm(value)}}
469 | />
470 |
471 |
472 |
473 | );
474 | }
475 |
476 | const styles = StyleSheet.create({
477 | container: {
478 | flex: 1,
479 | alignItems: 'center',
480 | justifyContent: 'center',
481 | verticalAlign: 'middle',
482 | backgroundColor: 'white',
483 | paddingHorizontal: 20,
484 | },
485 | customComponentContainer: {
486 | paddingHorizontal: 20,
487 | paddingVertical: 10,
488 | },
489 | text: {
490 | marginBottom: 20,
491 | },
492 | fixToText: {
493 | flexDirection: 'row',
494 | justifyContent: 'space-between',
495 | },
496 | tinyLogo: {
497 | width: 20,
498 | height: 20,
499 | },
500 | outerCircle: {
501 | borderRadius: 30 / 2,
502 | borderColor: 'green',
503 | borderWidth: 2,
504 | backgroundColor: 'white',
505 | flex: 1,
506 | justifyContent: 'center',
507 | alignItems: 'center',
508 | },
509 | innerCircle: {
510 | width: 15,
511 | height: 15,
512 | borderRadius: 15 / 2,
513 | backgroundColor: 'green',
514 | margin: 5,
515 | },
516 | radioButton: {
517 | width: 20,
518 | height: 20,
519 | borderRadius: 20 / 2,
520 | borderWidth: 3,
521 | borderColor: 'white',
522 | },
523 | avatarStyle: {
524 | height: 20,
525 | width: 20,
526 | borderRadius: 20,
527 | marginRight: 5,
528 | },
529 | itemStyle: {
530 | flexDirection: 'row',
531 | justifyContent: 'center',
532 | alignItems: 'center',
533 | },
534 | });
535 |
--------------------------------------------------------------------------------
/example/src/WithClassComponent.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {View, StyleSheet} from 'react-native';
3 | import DropdownSelect from 'react-native-input-select';
4 |
5 | // Define the type for our component props
6 | interface MyComponentProps {}
7 |
8 | // Define the type for our component state
9 | interface MyComponentState {
10 | country: any[];
11 | }
12 |
13 | // Class component
14 | class MyComponent extends React.Component {
15 | constructor(props: MyComponentProps) {
16 | super(props);
17 | this.state = {
18 | country: [],
19 | };
20 | }
21 |
22 | // Event handler
23 | setCountry(country: any) {
24 | this.setState({
25 | country,
26 | });
27 | }
28 |
29 | render() {
30 | const {country} = this.state;
31 |
32 | return (
33 |
34 | this.setCountry(itemValue)}
52 | isMultiple
53 | isSearchable
54 | />
55 |
56 | );
57 | }
58 | }
59 |
60 | const styles = StyleSheet.create({
61 | container: {
62 | flex: 1,
63 | justifyContent: 'center',
64 | alignItems: 'center',
65 | },
66 | });
67 |
68 | export default MyComponent;
69 |
--------------------------------------------------------------------------------
/example/src/data.ts:
--------------------------------------------------------------------------------
1 | export const countries = [
2 | {name: 'Albania', code: 'AL'},
3 | {name: 'Åland Islands', code: 'AX'},
4 | {name: 'Algeria', code: 'DZ'},
5 | {name: 'American Samoa', code: 'AS'},
6 | {name: 'Andorra', code: 'AD'},
7 | {name: 'Angola', code: 'AO'},
8 | {name: 'Anguilla', code: 'AI'},
9 | {name: 'Antarctica', code: 'AQ'},
10 | {name: 'Antigua and Barbuda', code: 'AG'},
11 | {name: 'Argentina', code: 'AR'},
12 | {name: 'Armenia', code: 'AM'},
13 | {name: 'Aruba', code: 'AW'},
14 | {name: 'Australia', code: 'AU'},
15 | {name: 'Austria', code: 'AT'},
16 | {name: 'Azerbaijan', code: 'AZ'},
17 | {name: 'Bahamas (the)', code: 'BS'},
18 | {name: 'Bahrain', code: 'BH'},
19 | {name: 'Bangladesh', code: 'BD'},
20 | {name: 'Barbados', code: 'BB'},
21 | {name: 'Belarus', code: 'BY'},
22 | {name: 'Belgium', code: 'BE'},
23 | {name: 'Belize', code: 'BZ'},
24 | {name: 'Benin', code: 'BJ'},
25 | {name: 'Bermuda', code: 'BM'},
26 | {name: 'Bhutan', code: 'BT'},
27 | {name: 'Bolivia (Plurinational State of)', code: 'BO'},
28 | {name: 'Bonaire, Sint Eustatius and Saba', code: 'BQ'},
29 | {name: 'Bosnia and Herzegovina', code: 'BA'},
30 | {name: 'Botswana', code: 'BW'},
31 | {name: 'Bouvet Island', code: 'BV'},
32 | {name: 'Brazil', code: 'BR'},
33 | {name: 'British Indian Ocean Territory (the)', code: 'IO'},
34 | {name: 'Brunei Darussalam', code: 'BN'},
35 | {name: 'Bulgaria', code: 'BG'},
36 | {name: 'Burkina Faso', code: 'BF'},
37 | {name: 'Burundi', code: 'BI'},
38 | {name: 'Cabo Verde', code: 'CV'},
39 | {name: 'Cambodia', code: 'KH'},
40 | {name: 'Cameroon', code: 'CM'},
41 | {name: 'Canada', code: 'CA'},
42 | {name: 'Cayman Islands (the)', code: 'KY'},
43 | {name: 'Central African Republic (the)', code: 'CF'},
44 | {name: 'Chad', code: 'TD'},
45 | {name: 'Chile', code: 'CL'},
46 | {name: 'China', code: 'CN'},
47 | {name: 'Christmas Island', code: 'CX'},
48 | {name: 'Cocos (Keeling) Islands (the)', code: 'CC'},
49 | {name: 'Colombia', code: 'CO'},
50 | {name: 'Comoros (the)', code: 'KM'},
51 | {name: 'Congo (the Democratic Republic of the)', code: 'CD'},
52 | {name: 'Congo (the)', code: 'CG'},
53 | {name: 'Cook Islands (the)', code: 'CK'},
54 | {name: 'Costa Rica', code: 'CR'},
55 | {name: 'Croatia', code: 'HR'},
56 | {name: 'Cuba', code: 'CU'},
57 | {name: 'Curaçao', code: 'CW'},
58 | {name: 'Cyprus', code: 'CY'},
59 | {name: 'Czechia', code: 'CZ'},
60 | {name: "Côte d'Ivoire", code: 'CI'},
61 | {name: 'Denmark', code: 'DK'},
62 | {name: 'Djibouti', code: 'DJ'},
63 | {name: 'Dominica', code: 'DM'},
64 | {name: 'Dominican Republic (the)', code: 'DO'},
65 | {name: 'Ecuador', code: 'EC'},
66 | {name: 'Egypt', code: 'EG'},
67 | {name: 'El Salvador', code: 'SV'},
68 | {name: 'Equatorial Guinea', code: 'GQ'},
69 | {name: 'Eritrea', code: 'ER'},
70 | {name: 'Estonia', code: 'EE'},
71 | {name: 'Eswatini', code: 'SZ'},
72 | {name: 'Ethiopia', code: 'ET'},
73 | {name: 'Falkland Islands (the) [Malvinas]', code: 'FK'},
74 | {name: 'Faroe Islands (the)', code: 'FO'},
75 | {name: 'Fiji', code: 'FJ'},
76 | {name: 'Finland', code: 'FI'},
77 | {name: 'France', code: 'FR'},
78 | {name: 'French Guiana', code: 'GF'},
79 | {name: 'French Polynesia', code: 'PF'},
80 | {name: 'French Southern Territories (the)', code: 'TF'},
81 | {name: 'Gabon', code: 'GA'},
82 | {name: 'Gambia (the)', code: 'GM'},
83 | {name: 'Georgia', code: 'GE'},
84 | {name: 'Germany', code: 'DE'},
85 | {name: 'Ghana', code: 'GH'},
86 | {name: 'Gibraltar', code: 'GI'},
87 | {name: 'Greece', code: 'GR'},
88 | {name: 'Greenland', code: 'GL'},
89 | {name: 'Grenada', code: 'GD'},
90 | {name: 'Guadeloupe', code: 'GP'},
91 | {name: 'Guam', code: 'GU'},
92 | {name: 'Guatemala', code: 'GT'},
93 | {name: 'Guernsey', code: 'GG'},
94 | {name: 'Guinea', code: 'GN'},
95 | {name: 'Guinea-Bissau', code: 'GW'},
96 | {name: 'Guyana', code: 'GY'},
97 | {name: 'Haiti', code: 'HT'},
98 | {name: 'Heard Island and McDonald Islands', code: 'HM'},
99 | {name: 'Holy See (the)', code: 'VA'},
100 | {name: 'Honduras', code: 'HN'},
101 | {name: 'Hong Kong', code: 'HK'},
102 | {name: 'Hungary', code: 'HU'},
103 | {name: 'Iceland', code: 'IS'},
104 | {name: 'India', code: 'IN'},
105 | {name: 'Indonesia', code: 'ID'},
106 | {name: 'Iran (Islamic Republic of)', code: 'IR'},
107 | {name: 'Iraq', code: 'IQ'},
108 | {name: 'Ireland', code: 'IE'},
109 | {name: 'Isle of Man', code: 'IM'},
110 | {name: 'Israel', code: 'IL'},
111 | {name: 'Italy', code: 'IT'},
112 | {name: 'Jamaica', code: 'JM'},
113 | {name: 'Japan', code: 'JP'},
114 | {name: 'Jersey', code: 'JE'},
115 | {name: 'Jordan', code: 'JO'},
116 | {name: 'Kazakhstan', code: 'KZ'},
117 | {name: 'Kenya', code: 'KE'},
118 | {name: 'Kiribati', code: 'KI'},
119 | {name: "Korea (the Democratic People's Republic of)", code: 'KP'},
120 | {name: 'Korea (the Republic of)', code: 'KR'},
121 | {name: 'Kuwait', code: 'KW'},
122 | {name: 'Kyrgyzstan', code: 'KG'},
123 | {name: "Lao People's Democratic Republic (the)", code: 'LA'},
124 | {name: 'Latvia', code: 'LV'},
125 | {name: 'Lebanon', code: 'LB'},
126 | {name: 'Lesotho', code: 'LS'},
127 | {name: 'Liberia', code: 'LR'},
128 | {name: 'Libya', code: 'LY'},
129 | {name: 'Liechtenstein', code: 'LI'},
130 | {name: 'Lithuania', code: 'LT'},
131 | {name: 'Luxembourg', code: 'LU'},
132 | {name: 'Macao', code: 'MO'},
133 | {name: 'Madagascar', code: 'MG'},
134 | {name: 'Malawi', code: 'MW'},
135 | {name: 'Malaysia', code: 'MY'},
136 | {name: 'Maldives', code: 'MV'},
137 | {name: 'Mali', code: 'ML'},
138 | {name: 'Malta', code: 'MT'},
139 | {name: 'Marshall Islands (the)', code: 'MH'},
140 | {name: 'Martinique', code: 'MQ'},
141 | {name: 'Mauritania', code: 'MR'},
142 | {name: 'Mauritius', code: 'MU'},
143 | {name: 'Mayotte', code: 'YT'},
144 | {name: 'Mexico', code: 'MX'},
145 | {name: 'Micronesia (Federated States of)', code: 'FM'},
146 | {name: 'Moldova (the Republic of)', code: 'MD'},
147 | {name: 'Monaco', code: 'MC'},
148 | {name: 'Mongolia', code: 'MN'},
149 | {name: 'Montenegro', code: 'ME'},
150 | {name: 'Montserrat', code: 'MS'},
151 | {name: 'Morocco', code: 'MA'},
152 | {name: 'Mozambique', code: 'MZ'},
153 | {name: 'Myanmar', code: 'MM'},
154 | {name: 'Namibia', code: 'NA'},
155 | {name: 'Nauru', code: 'NR'},
156 | {name: 'Nepal', code: 'NP'},
157 | {name: 'Netherlands (the)', code: 'NL'},
158 | {name: 'New Caledonia', code: 'NC'},
159 | {name: 'New Zealand', code: 'NZ'},
160 | {name: 'Nicaragua', code: 'NI'},
161 | {name: 'Niger (the)', code: 'NE'},
162 | {name: 'Nigeria', code: 'NG'},
163 | {name: 'Niue', code: 'NU'},
164 | {name: 'Norfolk Island', code: 'NF'},
165 | {name: 'Northern Mariana Islands (the)', code: 'MP'},
166 | {name: 'Norway', code: 'NO'},
167 | {name: 'Oman', code: 'OM'},
168 | {name: 'Pakistan', code: 'PK'},
169 | {name: 'Palau', code: 'PW'},
170 | {name: 'Palestine, State of', code: 'PS'},
171 | {name: 'Panama', code: 'PA'},
172 | {name: 'Papua New Guinea', code: 'PG'},
173 | {name: 'Paraguay', code: 'PY'},
174 | {name: 'Peru', code: 'PE'},
175 | {name: 'Philippines (the)', code: 'PH'},
176 | {name: 'Pitcairn', code: 'PN'},
177 | {name: 'Poland', code: 'PL'},
178 | {name: 'Portugal', code: 'PT'},
179 | {name: 'Puerto Rico', code: 'PR'},
180 | {name: 'Qatar', code: 'QA'},
181 | {name: 'Republic of North Macedonia', code: 'MK'},
182 | {name: 'Romania', code: 'RO'},
183 | {name: 'Russian Federation (the)', code: 'RU'},
184 | {name: 'Rwanda', code: 'RW'},
185 | {name: 'Réunion', code: 'RE'},
186 | {name: 'Saint Barthélemy', code: 'BL'},
187 | {name: 'Saint Helena, Ascension and Tristan da Cunha', code: 'SH'},
188 | {name: 'Saint Kitts and Nevis', code: 'KN'},
189 | {name: 'Saint Lucia', code: 'LC'},
190 | {name: 'Saint Martin (French part)', code: 'MF'},
191 | {name: 'Saint Pierre and Miquelon', code: 'PM'},
192 | {name: 'Saint Vincent and the Grenadines', code: 'VC'},
193 | {name: 'Samoa', code: 'WS'},
194 | {name: 'San Marino', code: 'SM'},
195 | {name: 'Sao Tome and Principe', code: 'ST'},
196 | {name: 'Saudi Arabia', code: 'SA'},
197 | {name: 'Senegal', code: 'SN'},
198 | {name: 'Serbia', code: 'RS'},
199 | {name: 'Seychelles', code: 'SC'},
200 | {name: 'Sierra Leone', code: 'SL'},
201 | {name: 'Singapore', code: 'SG'},
202 | {name: 'Sint Maarten (Dutch part)', code: 'SX'},
203 | {name: 'Slovakia', code: 'SK'},
204 | {name: 'Slovenia', code: 'SI'},
205 | {name: 'Solomon Islands', code: 'SB'},
206 | {name: 'Somalia', code: 'SO'},
207 | {name: 'South Africa', code: 'ZA'},
208 | {name: 'South Georgia and the South Sandwich Islands', code: 'GS'},
209 | {name: 'South Sudan', code: 'SS'},
210 | {name: 'Spain', code: 'ES'},
211 | {name: 'Sri Lanka', code: 'LK'},
212 | {name: 'Sudan (the)', code: 'SD'},
213 | {name: 'Suriname', code: 'SR'},
214 | {name: 'Svalbard and Jan Mayen', code: 'SJ'},
215 | {name: 'Sweden', code: 'SE'},
216 | {name: 'Switzerland', code: 'CH'},
217 | {name: 'Syrian Arab Republic', code: 'SY'},
218 | {name: 'Taiwan (Province of China)', code: 'TW'},
219 | {name: 'Tajikistan', code: 'TJ'},
220 | {name: 'Tanzania, United Republic of', code: 'TZ'},
221 | {name: 'Thailand', code: 'TH'},
222 | {name: 'Timor-Leste', code: 'TL'},
223 | {name: 'Togo', code: 'TG'},
224 | {name: 'Tokelau', code: 'TK'},
225 | {name: 'Tonga', code: 'TO'},
226 | {name: 'Trinidad and Tobago', code: 'TT'},
227 | {name: 'Tunisia', code: 'TN'},
228 | {name: 'Turkey', code: 'TR'},
229 | {name: 'Turkmenistan', code: 'TM'},
230 | {name: 'Turks and Caicos Islands (the)', code: 'TC'},
231 | {name: 'Tuvalu', code: 'TV'},
232 | {name: 'Uganda', code: 'UG'},
233 | {name: 'Ukraine', code: 'UA'},
234 | {name: 'United Arab Emirates (the)', code: 'AE'},
235 | {
236 | name: 'United Kingdom of Great Britain and Northern Ireland (the)',
237 | code: 'GB',
238 | },
239 | {name: 'United States Minor Outlying Islands (the)', code: 'UM'},
240 | {name: 'United States of America (the)', code: 'US'},
241 | {name: 'Uruguay', code: 'UY'},
242 | {name: 'Uzbekistan', code: 'UZ'},
243 | {name: 'Vanuatu', code: 'VU'},
244 | {name: 'Venezuela (Bolivarian Republic of)', code: 'VE'},
245 | {name: 'Viet Nam', code: 'VN'},
246 | {name: 'Virgin Islands (British)', code: 'VG'},
247 | {name: 'Virgin Islands (U.S.)', code: 'VI'},
248 | {name: 'Wallis and Futuna', code: 'WF'},
249 | {name: 'Western Sahara', code: 'EH'},
250 | {name: 'Yemen', code: 'YE'},
251 | {name: 'Zambia', code: 'ZM'},
252 | {name: 'Zimbabwe', code: 'ZW'},
253 | ];
254 |
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@react-native/typescript-config/tsconfig.json",
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "paths": {
6 | "react-native-input-select": ["../src/index"],
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/jest-setup.ts:
--------------------------------------------------------------------------------
1 | import '@testing-library/react-native/extend-expect';
2 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-input-select",
3 | "version": "2.1.3",
4 | "description": "A customizable dropdown selection package for react-native for android and iOS with multiple select and search capabilities.",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/src/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "react-native-select.podspec",
17 | "!lib/typescript/example",
18 | "!android/build",
19 | "!ios/build",
20 | "!**/__tests__",
21 | "!**/__fixtures__",
22 | "!**/__mocks__"
23 | ],
24 | "scripts": {
25 | "test": "jest",
26 | "test:coverage": "jest --coverage",
27 | "typescript": "tsc --noEmit",
28 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
29 | "prepare": "bob build",
30 | "release": "release-it --ci",
31 | "example": "yarn --cwd example",
32 | "pods": "cd example && pod-install --quiet",
33 | "bootstrap": "yarn example && yarn && yarn pods",
34 | "start": "yarn example start",
35 | "android": "yarn example android",
36 | "ios": "yarn example ios",
37 | "clean": "yarn example clean",
38 | "troubleshoot": "react-native doctor",
39 | "watchman:clear": "watchman watch-del-all"
40 | },
41 | "keywords": [
42 | "react-native",
43 | "ios",
44 | "android",
45 | "dropdown",
46 | "selection",
47 | "dropdown menu",
48 | "multiple select",
49 | "picker",
50 | "pull-down menu",
51 | "combo box",
52 | "list box"
53 | ],
54 | "repository": "https://github.com/azeezat/react-native-select",
55 | "author": "Azeezat (https://github.com/azeezat)",
56 | "license": "MIT",
57 | "bugs": {
58 | "url": "https://github.com/azeezat/react-native-select/issues"
59 | },
60 | "homepage": "https://github.com/azeezat/react-native-select#readme",
61 | "publishConfig": {
62 | "registry": "https://registry.npmjs.org/"
63 | },
64 | "devDependencies": {
65 | "@babel/plugin-transform-private-methods": "^7.24.7",
66 | "@babel/plugin-transform-private-property-in-object": "^7.24.7",
67 | "@babel/preset-typescript": "^7.24.7",
68 | "@commitlint/config-conventional": "^19.2.2",
69 | "@react-native-community/eslint-config": "^3.2.0",
70 | "@release-it/conventional-changelog": "^8.0.1",
71 | "@testing-library/jest-dom": "^6.4.8",
72 | "@testing-library/react-native": "^12.9.0",
73 | "@types/jest": "^29.5.12",
74 | "@types/react": "18.3.2",
75 | "@types/react-native": "^0.73.0",
76 | "commitlint": "^19.3.0",
77 | "eslint": "^8.0.0",
78 | "eslint-config-prettier": "^7.0.0",
79 | "eslint-plugin-prettier": "^3.1.3",
80 | "husky": "^9.0.11",
81 | "jest": "^29.7.0",
82 | "metro-react-native-babel-preset": "^0.77.0",
83 | "pod-install": "^0.2.2",
84 | "prettier": "^2.0.5",
85 | "react": "^18.3.1",
86 | "react-native": "^0.75.0",
87 | "react-native-builder-bob": "^0.23.2",
88 | "react-test-renderer": "^18.3.1",
89 | "release-it": "^17.2.1",
90 | "typescript": "^5.4.5"
91 | },
92 | "peerDependencies": {
93 | "react": "*",
94 | "react-native": "*"
95 | },
96 | "jest": {
97 | "preset": "react-native",
98 | "modulePathIgnorePatterns": [
99 | "/example/node_modules",
100 | "/lib/"
101 | ],
102 | "coverageReporters": [
103 | "html",
104 | "text",
105 | "lcov"
106 | ],
107 | "coverageThreshold": {
108 | "global": {
109 | "branches": 94,
110 | "functions": 94,
111 | "lines": 94,
112 | "statements": 94
113 | }
114 | }
115 | },
116 | "commitlint": {
117 | "extends": [
118 | "@commitlint/config-conventional"
119 | ]
120 | },
121 | "eslintConfig": {
122 | "root": true,
123 | "extends": [
124 | "@react-native-community",
125 | "prettier"
126 | ],
127 | "rules": {
128 | "prettier/prettier": [
129 | "error",
130 | {
131 | "quoteProps": "consistent",
132 | "singleQuote": true,
133 | "tabWidth": 2,
134 | "trailingComma": "es5",
135 | "useTabs": false
136 | }
137 | ]
138 | }
139 | },
140 | "eslintIgnore": [
141 | "node_modules/",
142 | "lib/",
143 | "coverage/",
144 | "src/__tests__/**"
145 | ],
146 | "prettier": {
147 | "quoteProps": "consistent",
148 | "singleQuote": true,
149 | "tabWidth": 2,
150 | "trailingComma": "es5",
151 | "useTabs": false
152 | },
153 | "react-native-builder-bob": {
154 | "source": "src",
155 | "output": "lib",
156 | "targets": [
157 | "commonjs",
158 | "module",
159 | [
160 | "typescript",
161 | {
162 | "project": "tsconfig.build.json"
163 | }
164 | ]
165 | ]
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/pull_request_template.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | Please include a summary of the changes and the related issue. Please also include relevant motivation and context. List any dependencies that are required for this change.
4 |
5 | Fixes # (issue)
6 |
7 | ## Type of change
8 |
9 | Please delete options that are not relevant.
10 |
11 | - [ ] Bug fix (non-breaking change which fixes an issue)
12 | - [ ] New feature (non-breaking change which adds functionality)
13 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
14 | - [ ] This change requires a documentation update
15 |
16 | # How Has This Been Tested?
17 |
18 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
19 |
20 | - [ ] Test A
21 | - [ ] Test B
22 |
23 | **Test Configuration**:
24 | * Firmware version:
25 | * Hardware:
26 | * Toolchain:
27 | * SDK:
28 |
29 | # Checklist:
30 |
31 | - [ ] My code follows the style guidelines of this project
32 | - [ ] I have performed a self-review of my code
33 | - [ ] I have commented my code, particularly in hard-to-understand areas
34 | - [ ] I have made corresponding changes to the documentation
35 | - [ ] My changes generate no new warnings
36 | - [ ] I have added tests that prove my fix is effective or that my feature works
37 | - [ ] New and existing unit tests pass locally with my changes
38 |
39 |
--------------------------------------------------------------------------------
/scripts/bootstrap.js:
--------------------------------------------------------------------------------
1 | const os = require('os');
2 | const path = require('path');
3 | const child_process = require('child_process');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const args = process.argv.slice(2);
7 | const options = {
8 | cwd: process.cwd(),
9 | env: process.env,
10 | stdio: 'inherit',
11 | encoding: 'utf-8',
12 | };
13 |
14 | if (os.type() === 'Windows_NT') {
15 | options.shell = true;
16 | }
17 |
18 | let result;
19 |
20 | if (process.cwd() !== root || args.length) {
21 | // We're not in the root of the project, or additional arguments were passed
22 | // In this case, forward the command to `yarn`
23 | result = child_process.spawnSync('yarn', args, options);
24 | } else {
25 | // If `yarn` is run without arguments, perform bootstrap
26 | result = child_process.spawnSync('yarn', ['bootstrap'], options);
27 | }
28 |
29 | process.exitCode = result.status;
30 |
--------------------------------------------------------------------------------
/src/__tests__/empty-dropdown.test.tsx:
--------------------------------------------------------------------------------
1 | import React, { createRef } from 'react';
2 | import DropdownSelect from '../index';
3 | import { render, screen, userEvent } from '@testing-library/react-native';
4 | import '@testing-library/jest-dom';
5 | import { PlatformOSType, Pressable, Text } from 'react-native';
6 | import { DropdownSelectHandle } from 'src/types/index.types';
7 |
8 | export const mockPlatform = (OS: PlatformOSType) => {
9 | jest.doMock('react-native/Libraries/Utilities/Platform', () => ({
10 | OS,
11 | select: (config: { [x: string]: any }) => config[OS],
12 | }));
13 | };
14 |
15 | describe('Initial state of component', () => {
16 | beforeAll(() => {
17 | jest.useFakeTimers();
18 | });
19 |
20 | afterAll(() => {
21 | jest.useRealTimers();
22 | });
23 |
24 | const user = userEvent.setup();
25 |
26 | // TODO: test these mocks once you are able to simulate specific device types like android and iOS
27 | const mockOpenModal = jest.fn();
28 | const mockCloseModal = jest.fn();
29 |
30 | const testId = 'some-random-test-id';
31 | const placeholder = 'Select an option';
32 | const error = 'This is an error';
33 | const helperText = 'This is an helper text';
34 |
35 | const defaultDropdown = (
36 | {}}
41 | testID={testId}
42 | modalControls={{
43 | modalProps: {
44 | onShow: mockOpenModal,
45 | onDismiss: mockCloseModal,
46 | },
47 | }}
48 | error={error}
49 | />
50 | );
51 |
52 | test('show default texts', () => {
53 | render(defaultDropdown);
54 | const entireDropdown = screen.getByTestId(testId);
55 | expect(entireDropdown);
56 | expect(screen.getByText(placeholder));
57 | expect(screen.getByText(error));
58 | });
59 |
60 | test('show default styles', () => {
61 | render(defaultDropdown);
62 | const placeholderStyle = screen.getByText(placeholder);
63 | expect(placeholderStyle.props.style).toMatchObject([
64 | { color: '#000000' },
65 | undefined,
66 | ]);
67 | });
68 |
69 | test('open and close modal', async () => {
70 | mockPlatform('android');
71 |
72 | render(defaultDropdown);
73 |
74 | //open modal when dropdown is clicked
75 | await user.press(screen.getByText(placeholder));
76 | expect(screen.getByText('No options available'));
77 |
78 | // close the modal after opening
79 | const closeModal = screen.getByLabelText('close modal');
80 | await user.press(closeModal);
81 | expect(screen.getByText(placeholder));
82 |
83 | //check if callback was called on android
84 | expect(mockCloseModal).toHaveBeenCalledTimes(1);
85 | });
86 |
87 | test('should open and close modal with useRef', async () => {
88 | mockPlatform('android');
89 | const dropdownRef = createRef();
90 | render(
91 | <>
92 | dropdownRef.current?.open()}>
93 | Open Modal
94 |
95 |
96 | {}}
101 | testID={testId}
102 | modalControls={{
103 | modalProps: {
104 | onShow: mockOpenModal,
105 | onDismiss: mockCloseModal,
106 | },
107 | }}
108 | ref={dropdownRef}
109 | listHeaderComponent={
110 | dropdownRef.current?.close()}>
111 | Close Modal
112 |
113 | }
114 | />
115 | >
116 | );
117 | await user.press(screen.getByText('Open Modal'));
118 | expect(screen.getByText('No options available'));
119 | await user.press(screen.getByText('Close Modal'));
120 | expect(mockCloseModal).toHaveBeenCalled();
121 | });
122 |
123 | const disabledDropdown = (
124 | {}}
128 | modalControls={{
129 | modalProps: {
130 | onShow: mockOpenModal,
131 | onDismiss: mockCloseModal,
132 | },
133 | }}
134 | disabled
135 | helperText={helperText}
136 | />
137 | );
138 |
139 | test('helper text', async () => {
140 | render(disabledDropdown);
141 | expect(screen.getByText(helperText));
142 | });
143 |
144 | test('Disabled dropdown should not be clickable', async () => {
145 | render(disabledDropdown);
146 |
147 | let dropdownInput = screen.getByTestId(
148 | 'react-native-input-select-dropdown-input-container'
149 | );
150 | await user.press(dropdownInput);
151 |
152 | expect(screen.queryByText('Close Modal')).toBeNull();
153 | expect(dropdownInput.props?.accessibilityState?.disabled).toBe(true);
154 | });
155 | });
156 |
--------------------------------------------------------------------------------
/src/__tests__/flat-list-dropdown.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import DropdownSelect from '../index';
3 | import { render, screen, userEvent } from '@testing-library/react-native';
4 | import '@testing-library/jest-dom';
5 | import { TFlatList } from 'src/types/index.types';
6 | import { Text } from 'react-native';
7 |
8 | describe('Flat List', () => {
9 | beforeAll(() => {
10 | jest.useFakeTimers();
11 | });
12 |
13 | afterAll(() => {
14 | jest.useRealTimers();
15 | });
16 |
17 | const user = userEvent.setup();
18 |
19 | const options: TFlatList = [
20 | { name: '🍛 Rice', value: '1', disabled: true },
21 | { name: 🍗 Chicken, value: '2' },
22 | { name: '🥦 Brocoli', value: '3', disabled: true },
23 | { name: '🍕 Pizza', value: '4' },
24 | ];
25 |
26 | const placeholder = 'Select food';
27 | const testId = 'section-list-test-id';
28 | const mockOnValueChange = jest.fn();
29 | const mockSearchCallback = jest.fn();
30 | const mockSelectAllCallback = jest.fn();
31 | const mockUnselectAllCallback = jest.fn();
32 |
33 | const flatListDropdown = (
34 |
48 | );
49 |
50 | describe('Initial state of component', () => {
51 | test('show default texts', () => {
52 | render(flatListDropdown);
53 | expect(screen.getByTestId(testId));
54 | expect(screen.getByText(placeholder));
55 | });
56 |
57 | test('show default styles', () => {
58 | render(flatListDropdown);
59 | const placeholderStyle = screen.getByText(placeholder);
60 | expect(placeholderStyle.props.style).toMatchObject([
61 | { color: '#000000' },
62 | undefined,
63 | ]);
64 | });
65 |
66 | test('search', async () => {
67 | render(flatListDropdown);
68 |
69 | //open modal
70 | await user.press(screen.getByText(placeholder));
71 |
72 | let totalCount = 0;
73 |
74 | //search non-existent item
75 | const searchPlaceholder = 'Search anything here';
76 | const searchBox = screen.getByPlaceholderText(searchPlaceholder);
77 | let text = 'hello';
78 | await user.type(searchBox, text);
79 | totalCount += text.length;
80 | screen.getByText('No options available');
81 | expect(mockSearchCallback).toHaveBeenCalledTimes(totalCount);
82 |
83 | //search existent item
84 | text = 'rice';
85 | await user.clear(searchBox);
86 | await user.type(searchBox, text);
87 | totalCount += text.length;
88 | screen.getByText(text, { exact: false });
89 | expect(mockSearchCallback).toHaveBeenCalledTimes(totalCount);
90 | });
91 | });
92 |
93 | describe('Single select', () => {
94 | test('open modal when dropdown is clicked and select a single item', async () => {
95 | render(flatListDropdown);
96 | await user.press(screen.getByText(placeholder));
97 | expect(screen.getByText(options[0].name as string));
98 | const optionToTestFor = screen.getByText('Chicken', { exact: false });
99 |
100 | expect(optionToTestFor);
101 |
102 | //select one option
103 | await user.press(optionToTestFor);
104 | expect(mockOnValueChange).toHaveBeenCalledTimes(1);
105 | });
106 |
107 | test('select an option from dropdown and click selected item to reopen modal.', async () => {
108 | render(flatListDropdown);
109 |
110 | //open modal
111 | await user.press(screen.getByText(placeholder));
112 |
113 | // select one option
114 | let selectedOptionLabel = screen.getByLabelText('Pizza', {
115 | exact: false,
116 | });
117 | await user.press(selectedOptionLabel);
118 |
119 | // click selected
120 | let selectedOption = screen.getByText('Pizza', { exact: false });
121 | expect(selectedOption);
122 | await user.press(selectedOption);
123 |
124 | //modal should be open
125 | expect(screen.getByTestId('react-native-input-select-modal'));
126 | });
127 |
128 | test('autoCloseOnSelect=false should not close modal after selection', async () => {
129 | const mockOnValueChange2 = jest.fn();
130 | const flatListDropdownWithAutoClose = (
131 |
140 | );
141 |
142 | render(flatListDropdownWithAutoClose);
143 | await user.press(screen.getByText(placeholder));
144 |
145 | // select single option without closing the modal
146 | await user.press(screen.getByText(options[0].name as string));
147 | // expect(mockOnValueChange2).toHaveBeenCalledTimes(1);
148 | screen.getByTestId('react-native-input-select-flat-list');
149 | });
150 |
151 | test('dropdown has an initial state', async () => {
152 | const initialSelection = options[3];
153 | const initialSelectionValue = initialSelection.value as string;
154 | const initialSelectionLabel = initialSelection.name as string;
155 |
156 | const flatListDropdownWithInitialState = (
157 | {}}
161 | placeholder={placeholder}
162 | optionLabel="name"
163 | optionValue="value"
164 | />
165 | );
166 |
167 | const { rerender } = render(flatListDropdownWithInitialState);
168 |
169 | // open modal
170 | await user.press(
171 | screen.getByText(initialSelectionLabel, { exact: false })
172 | );
173 |
174 | //unselect
175 | await user.press(
176 | screen.getByLabelText(initialSelectionLabel, { exact: false })
177 | );
178 |
179 | rerender(
180 | {}}
184 | placeholder={placeholder}
185 | optionLabel="name"
186 | optionValue="value"
187 | />
188 | );
189 |
190 | await user.press(screen.getByText(placeholder));
191 | });
192 | });
193 |
194 | describe('Multiple select', () => {
195 | const mockOnValueChangeMultiSelect = jest.fn();
196 |
197 | const flatListDropdownWithMultiSelect = (
198 |
213 | );
214 |
215 | test('open modal when dropdown is clicked and select a multiple items', async () => {
216 | render(flatListDropdownWithMultiSelect);
217 | await user.press(screen.getByText(placeholder));
218 |
219 | // select multiple options
220 | const firstSelection = screen.getByText(options[0].name as string); // This value has been disabled, so no call is expected
221 | expect(firstSelection);
222 | await user.press(firstSelection);
223 |
224 | const secondSelection = screen.getByText('Chicken', { exact: false });
225 | expect(secondSelection);
226 | await user.press(secondSelection);
227 |
228 | const thirdSelection = screen.getByText(options[2].name as string); // This value has been disabled, so no call is expected
229 | expect(thirdSelection);
230 | await user.press(thirdSelection);
231 |
232 | const forthSelection = screen.getByText(options[3].name as string);
233 | expect(forthSelection);
234 | await user.press(forthSelection);
235 |
236 | expect(mockOnValueChangeMultiSelect).toHaveBeenCalledTimes(2);
237 |
238 | //`Clear All` should now be visible since all items in the list have been selected
239 | screen.getByText('Clear all');
240 | });
241 |
242 | test('select option from dropdown and click selected item to reopen modal.', async () => {
243 | render(flatListDropdownWithMultiSelect);
244 |
245 | //open modal
246 | await user.press(screen.getByText(placeholder));
247 |
248 | // select one option
249 | let selectedOptionLabel = screen.getByLabelText('Pizza', {
250 | exact: false,
251 | });
252 | await user.press(selectedOptionLabel);
253 |
254 | // close the modal
255 | const closeModal = screen.getByLabelText('close modal');
256 | await user.press(closeModal);
257 |
258 | // click selected
259 | let selectedOption = screen.getByText('Pizza', { exact: false });
260 | expect(selectedOption);
261 | await user.press(selectedOption);
262 |
263 | //modal should be open
264 | expect(screen.getByTestId('react-native-input-select-modal'));
265 | });
266 |
267 | test('dropdown has an initial state', async () => {
268 | const initialSelection = options[3];
269 | const initialSelectionValue = initialSelection.value as string;
270 | const initialSelectionLabel = initialSelection.name as string;
271 |
272 | const flatListDropdownWithInitialState = (
273 | {}}
277 | placeholder={placeholder}
278 | optionLabel="name"
279 | optionValue="value"
280 | isMultiple
281 | />
282 | );
283 |
284 | const { rerender } = render(flatListDropdownWithInitialState);
285 |
286 | // open modal
287 | await user.press(
288 | screen.getByText(initialSelectionLabel, { exact: false })
289 | );
290 |
291 | //unselect
292 | await user.press(
293 | screen.getByLabelText(initialSelectionLabel, { exact: false })
294 | );
295 |
296 | // close the modal
297 | const closeModal = screen.getByLabelText('close modal');
298 | await user.press(closeModal);
299 |
300 | rerender(
301 | {}}
305 | placeholder={placeholder}
306 | optionLabel="name"
307 | optionValue="value"
308 | isMultiple
309 | />
310 | );
311 |
312 | await user.press(screen.getByText(placeholder));
313 | });
314 |
315 | test('select all / unselect all', async () => {
316 | render(flatListDropdownWithMultiSelect);
317 | await user.press(screen.getByText(placeholder));
318 |
319 | // select all
320 | const selectAll = screen.getByText('Select all');
321 | await user.press(selectAll);
322 | expect(mockSelectAllCallback).toHaveBeenCalledTimes(1);
323 |
324 | // unselect all
325 | const clearAll = screen.getByText('Clear all'); //`Clear all` should now be visible since all items in the list have been selected
326 | await user.press(clearAll);
327 | expect(mockUnselectAllCallback).toHaveBeenCalledTimes(1); //`Select all` should now be visible since all items in the list have been deselected
328 | screen.getByText('Select all'); //`Select all` should now be visible since all items in the list have been deselected
329 | });
330 | });
331 |
332 | test('auto scroll to index of selected item in flat list', async () => {
333 | const selectedItem = options[3];
334 |
335 | const flatListDropdownWithMultiSelectWithSelectedItem = (
336 | {}}
340 | testID="section-list-test-id"
341 | placeholder={placeholder}
342 | optionLabel="name"
343 | isMultiple
344 | />
345 | );
346 | render(flatListDropdownWithMultiSelectWithSelectedItem);
347 | await user.press(
348 | screen.getByTestId('react-native-input-select-dropdown-input-container')
349 | );
350 |
351 | const itemCount = screen.getAllByText(selectedItem.name as string);
352 | expect(itemCount.length).toBe(2); //since the item is selected, it would show on the dropdown container hence the reason we have two items
353 | });
354 | });
355 |
--------------------------------------------------------------------------------
/src/__tests__/section-list-dropdown.test.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import DropdownSelect from '../index';
3 | import { render, screen, userEvent } from '@testing-library/react-native';
4 | import '@testing-library/jest-dom';
5 | import { TSectionList } from '../types/index.types';
6 | import { extractPropertyFromArray, removeDisabledItems } from '../utils';
7 |
8 | const selectAllOptions = (options: TSectionList) => {
9 | const modifiedSectionData = extractPropertyFromArray(options, 'data')?.flat();
10 | let val = removeDisabledItems(modifiedSectionData);
11 | return val.map((item) => item.label as string);
12 | };
13 |
14 | describe('Section list', () => {
15 | beforeAll(() => {
16 | jest.useFakeTimers();
17 | });
18 |
19 | afterAll(() => {
20 | jest.useRealTimers();
21 | });
22 |
23 | const user = userEvent.setup();
24 |
25 | const placeholder = 'Select an option';
26 | const mockOnValueChange = jest.fn();
27 | const mockSearchCallback = jest.fn();
28 | const mockSelectAllCallback = jest.fn();
29 | const mockUnselectAllCallback = jest.fn();
30 |
31 | const options: TSectionList = [
32 | {
33 | title: 'Main dishes',
34 | data: [
35 | { label: 'Pizza', value: 0 },
36 | { label: 'Burger', value: 1 },
37 | { label: 'Risotto', value: 2 },
38 | ],
39 | },
40 | {
41 | title: 'Sides',
42 | data: [
43 | { label: 'Ice cream', value: 3 },
44 | { label: 'Cheesecake', value: 4 },
45 | ],
46 | },
47 | {
48 | title: 'Drinks',
49 | data: [
50 | { label: 'Water', value: 5, disabled: true },
51 | { label: 'Coke', value: 6 },
52 | { label: 'Juice', value: 7 },
53 | ],
54 | },
55 | ];
56 |
57 | const sectionListDropdown = (
58 |
69 | );
70 | describe('Initial state of component', () => {
71 | test('show default texts', () => {
72 | render(sectionListDropdown);
73 | expect(screen.getByTestId('section-list-test-id'));
74 | expect(screen.getByText('Select an option'));
75 | });
76 |
77 | test('show default styles', () => {
78 | render(sectionListDropdown);
79 | const placeholderStyle = screen.getByText('Select an option');
80 | expect(placeholderStyle.props.style).toMatchObject([
81 | { color: '#000000' },
82 | undefined,
83 | ]);
84 | });
85 |
86 | test('search', async () => {
87 | render(sectionListDropdown);
88 |
89 | //open modal
90 | await user.press(screen.getByText(placeholder));
91 |
92 | let totalCount = 0;
93 |
94 | //search non-existent item
95 | const searchPlaceholder = 'Search anything here';
96 | const searchBox = screen.getByPlaceholderText(searchPlaceholder);
97 | let text = 'hello';
98 | await user.type(searchBox, text);
99 | totalCount += text.length;
100 | expect(mockSearchCallback).toHaveBeenCalledTimes(totalCount);
101 |
102 | //search existent item
103 | text = 'pizza';
104 | await user.clear(searchBox);
105 | await user.type(searchBox, text);
106 | totalCount += text.length;
107 | screen.getByText(text, { exact: false });
108 | expect(mockSearchCallback).toHaveBeenCalledTimes(totalCount);
109 | });
110 |
111 | test('toggle section list title', async () => {
112 | render(sectionListDropdown);
113 |
114 | //open modal
115 | await user.press(screen.getByText(placeholder));
116 |
117 | //close accordion, hides submenu
118 | const title = options[0].title;
119 | const titleBox = screen.getByText(title);
120 |
121 | await user.press(titleBox);
122 | const subMenuItem = options[0].data[0].label as string;
123 | expect(screen.queryByText(subMenuItem)).toBeNull();
124 |
125 | //open accordion, shows submenu
126 | await user.press(titleBox);
127 | expect(screen.getByText(subMenuItem));
128 | });
129 | });
130 |
131 | describe('Single select', () => {
132 | test('open modal when dropdown is clicked and select a single item', async () => {
133 | render(sectionListDropdown);
134 | await user.press(screen.getByText(placeholder));
135 | expect(screen.getByText(options[0].data[0].label as string));
136 | const optionToTestFor = screen.getByText(
137 | options[0].data[2].label as string,
138 | { exact: false }
139 | );
140 |
141 | expect(optionToTestFor);
142 |
143 | //select one option
144 | await user.press(optionToTestFor);
145 | expect(mockOnValueChange).toHaveBeenCalledTimes(1);
146 | });
147 | });
148 |
149 | describe('Multiple select', () => {
150 | let mockOnValueChangeMultiSelect = jest.fn();
151 |
152 | const sectionListDropdownWithMultiSelect = (
153 |
166 | );
167 |
168 | // TODO: revisit
169 | test.skip('open modal when dropdown is clicked and select a multiple items', async () => {
170 | render(sectionListDropdownWithMultiSelect);
171 | await user.press(screen.getByText(placeholder));
172 |
173 | let count = 0;
174 |
175 | // if there is a disabled item in the list, expect no call
176 | options.map(async (section) => {
177 | section.data.map(async (item) => {
178 | const listItem = screen.getByText(item?.label as string);
179 | expect(listItem);
180 | await user.press(listItem);
181 | if (!item.disabled) {
182 | count += 1;
183 | }
184 | });
185 | });
186 |
187 | expect(mockOnValueChangeMultiSelect).toHaveBeenCalledTimes(count);
188 |
189 | //`Clear All` should now be visible since all items in the list have been selected
190 | screen.getByText('Clear all');
191 | });
192 |
193 | test('select option from dropdown and click selected item to reopen modal.', async () => {
194 | render(sectionListDropdownWithMultiSelect);
195 |
196 | //open modal
197 | await user.press(screen.getByText(placeholder));
198 |
199 | // select one option
200 | let selectedOptionLabel = screen.getByLabelText('Pizza', {
201 | exact: false,
202 | });
203 | await user.press(selectedOptionLabel);
204 |
205 | // close the modal
206 | const closeModal = screen.getByLabelText('close modal');
207 | await user.press(closeModal);
208 |
209 | // click selected
210 | let selectedOption = screen.getByText('Pizza', { exact: false });
211 | expect(selectedOption);
212 | await user.press(selectedOption);
213 |
214 | //modal should be open
215 | expect(screen.getByTestId('react-native-input-select-modal'));
216 | });
217 |
218 | test('select all / unselect all', async () => {
219 | const { rerender } = render(sectionListDropdownWithMultiSelect);
220 | await user.press(
221 | screen.getByTestId('react-native-input-select-dropdown-input-container')
222 | );
223 |
224 | // select all
225 | const selectAll = screen.getByText('Select all');
226 | await user.press(selectAll);
227 | expect(mockSelectAllCallback).toHaveBeenCalledTimes(1);
228 |
229 | //N.B There is a useEffect hook that check if all the items are actually selected hence the reason for rerendering
230 | // Rerender the component with updated `selectedValue` prop
231 | rerender(
232 |
245 | );
246 |
247 | // unselect all
248 | const clearAll = screen.getByText('Clear all'); //`Clear all` should now be visible since all items in the list have been selected
249 | await user.press(clearAll);
250 | expect(mockUnselectAllCallback).toHaveBeenCalledTimes(1);
251 | });
252 | });
253 |
254 | test('auto scroll to index of selected item in section list', async () => {
255 | const selectedItem = options[0].data[2];
256 |
257 | const flatListDropdownWithMultiSelectWithSelectedItem = (
258 | {}}
262 | placeholder={placeholder}
263 | isMultiple
264 | />
265 | );
266 | render(flatListDropdownWithMultiSelectWithSelectedItem);
267 | await user.press(
268 | screen.getByTestId('react-native-input-select-dropdown-input-container')
269 | );
270 |
271 | const itemCount = screen.getAllByText(selectedItem.label as string);
272 | expect(itemCount.length).toBe(2); //since the item is selected, it would show on the dropdown container hence the reason we have two items
273 | });
274 | });
275 |
--------------------------------------------------------------------------------
/src/asset/arrow-down.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/src/asset/arrow-down.png
--------------------------------------------------------------------------------
/src/asset/check.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azeezat/react-native-select/ee40ab0230f88f52a564124f5c8f445a39525294/src/asset/check.png
--------------------------------------------------------------------------------
/src/components/CheckBox/checkbox.types.ts:
--------------------------------------------------------------------------------
1 | import type { ColorValue } from 'react-native';
2 | import { TCheckboxControls } from '../../types/index.types';
3 |
4 | export type CheckboxProps = {
5 | label?: string;
6 | value?: boolean;
7 | disabled?: boolean;
8 | primaryColor?: ColorValue;
9 | onChange?: (value: boolean | string | number) => void;
10 | } & { checkboxControls?: TCheckboxControls };
11 |
--------------------------------------------------------------------------------
/src/components/CheckBox/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Pressable, Text, StyleSheet, Image, View } from 'react-native';
3 | import { colors } from '../../styles/colors';
4 | import { CHECKBOX_SIZE } from '../../constants';
5 | import { CheckboxProps } from './checkbox.types';
6 |
7 | const CheckBox = ({
8 | label,
9 | value,
10 | disabled,
11 | primaryColor,
12 | checkboxControls,
13 | onChange,
14 | }: CheckboxProps) => {
15 | const {
16 | checkboxSize,
17 | checkboxComponent,
18 | checkboxDisabledStyle,
19 | checkboxStyle,
20 | checkboxUnselectedColor,
21 | checkboxLabelStyle,
22 | } = checkboxControls ?? {};
23 |
24 | const fillColor = {
25 | backgroundColor: disabled
26 | ? checkboxDisabledStyle?.backgroundColor || colors.disabled
27 | : value
28 | ? checkboxStyle?.backgroundColor || primaryColor
29 | : checkboxUnselectedColor || 'white',
30 | borderColor: disabled
31 | ? checkboxDisabledStyle?.borderColor || colors.disabled
32 | : checkboxStyle?.borderColor || styles.checkbox.borderColor,
33 | };
34 | label = typeof label === 'object' ? label : String(label);
35 | return (
36 | onChange(!value) : null}
38 | style={[styles.checkboxContainer]}
39 | disabled={disabled}
40 | aria-label={typeof label === 'string' ? label : ''}
41 | >
42 |
46 | {checkboxComponent || (
47 |
56 | )}
57 |
58 | {label && label !== '' && (
59 | {label}
60 | )}
61 |
62 | );
63 | };
64 |
65 | const styles = StyleSheet.create({
66 | checkboxContainer: {
67 | flexDirection: 'row',
68 | flexWrap: 'nowrap',
69 | alignItems: 'center',
70 | },
71 | checkbox: {
72 | padding: 4,
73 | borderWidth: 1,
74 | borderStyle: 'solid',
75 | borderRadius: 4,
76 | borderColor: 'black',
77 | },
78 | labelStyle: { marginLeft: 10 },
79 | });
80 |
81 | export default CheckBox;
82 |
--------------------------------------------------------------------------------
/src/components/CustomModal/index.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react-native/no-inline-styles */
2 | import React, { PropsWithChildren, ReactElement } from 'react';
3 | import {
4 | KeyboardAvoidingView,
5 | Modal,
6 | ModalProps,
7 | Platform,
8 | SafeAreaView,
9 | StyleSheet,
10 | TouchableOpacity,
11 | TouchableWithoutFeedback,
12 | } from 'react-native';
13 | import { colors } from '../../styles/colors';
14 | import { TCustomModalControls } from 'src/types/index.types';
15 |
16 | // In iOS, `SafeAreaView` does not automatically account on keyboard.
17 | // Therefore, for iOS we need to wrap the content in `KeyboardAvoidingView`.
18 | const ModalContentWrapper = ({ children }: PropsWithChildren): ReactElement => {
19 | return Platform.OS === 'ios' ? (
20 |
21 | {children}
22 |
23 | ) : (
24 | <>{children}>
25 | );
26 | };
27 |
28 | const CustomModal = ({
29 | visible,
30 | modalControls,
31 | children,
32 | onRequestClose,
33 | }: {
34 | modalControls?: TCustomModalControls;
35 | } & ModalProps) => {
36 | return (
37 |
44 | {/*Used to fix the select with search box behavior in iOS*/}
45 |
46 |
55 | {/* Added this `TouchableWithoutFeedback` wrapper because of the closing modal on expo web */}
56 |
57 |
64 | {children}
65 |
66 |
67 |
68 |
69 |
70 | );
71 | };
72 |
73 | const styles = StyleSheet.create({
74 | modalContainer: {
75 | flex: 1,
76 | justifyContent: 'flex-end',
77 | },
78 | modalBackgroundStyle: { backgroundColor: 'rgba(0, 0, 0, 0.5)' },
79 | modalOptionsContainer: {
80 | maxHeight: '50%',
81 | backgroundColor: colors.white,
82 | borderTopLeftRadius: 16,
83 | borderTopRightRadius: 16,
84 | zIndex: 5,
85 | },
86 | });
87 |
88 | export default CustomModal;
89 |
--------------------------------------------------------------------------------
/src/components/Dropdown/Dropdown.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { View, Text, StyleSheet } from 'react-native';
3 | import DropdownSelectedItemsView from './DropdownSelectedItemsView';
4 | import { colors } from '../../styles/colors';
5 | import { typography } from '../../styles/typography';
6 |
7 | const Dropdown = ({
8 | testID,
9 | label,
10 | placeholder,
11 | helperText,
12 | error,
13 | labelsOfSelectedItems,
14 | openModal,
15 | closeModal,
16 | isMultiple,
17 | selectedItem,
18 | selectedItems,
19 | dropdownIcon,
20 | labelStyle,
21 | dropdownStyle,
22 | dropdownIconStyle,
23 | dropdownContainerStyle,
24 | selectedItemStyle,
25 | placeholderStyle,
26 | multipleSelectedItemStyle,
27 | dropdownErrorStyle,
28 | dropdownErrorTextStyle,
29 | dropdownHelperTextStyle,
30 | primaryColor,
31 | disabled,
32 | setIndexOfSelectedItem,
33 | }: any) => {
34 | return (
35 |
41 | {label && label !== '' && (
42 | {label}
43 | )}
44 |
45 |
65 |
66 | {error && error !== '' && (
67 | {error}
68 | )}
69 |
70 | {helperText && helperText !== '' && !error && (
71 |
72 | {helperText}
73 |
74 | )}
75 |
76 | );
77 | };
78 |
79 | const styles = StyleSheet.create({
80 | label: { marginBottom: 16, color: colors.gray, ...typography.caption },
81 | error: { color: colors.red, marginTop: 8, ...typography.caption },
82 | helper: { marginTop: 8, color: colors.primary, ...typography.caption },
83 | dropdownInputContainer: { marginBottom: 23, width: '100%' },
84 | blackText: { color: colors.black },
85 | });
86 |
87 | export default Dropdown;
88 |
--------------------------------------------------------------------------------
/src/components/Dropdown/DropdownListItem.tsx:
--------------------------------------------------------------------------------
1 | import React, { memo } from 'react';
2 | import { TouchableOpacity, StyleSheet } from 'react-native';
3 | import CheckBox from '../CheckBox';
4 |
5 | const DropdownListItem = ({
6 | item,
7 | optionLabel,
8 | optionValue,
9 | isMultiple,
10 | selectedOption,
11 | onChange,
12 | primaryColor,
13 | checkboxControls,
14 | }: any) => {
15 | return (
16 | {} : () => onChange(item[optionValue])}
19 | >
20 | onChange(item[optionValue])}
28 | primaryColor={primaryColor}
29 | checkboxControls={checkboxControls}
30 | disabled={item.disabled}
31 | />
32 |
33 | );
34 | };
35 |
36 | const styles = StyleSheet.create({
37 | listItemContainerStyle: {
38 | paddingHorizontal: 20,
39 | paddingVertical: 10,
40 | flexDirection: 'row',
41 | alignItems: 'center',
42 | },
43 | });
44 |
45 | export default memo(DropdownListItem);
46 |
--------------------------------------------------------------------------------
/src/components/Dropdown/DropdownSelectedItemsView.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {
3 | View,
4 | Text,
5 | Pressable,
6 | ScrollView,
7 | StyleSheet,
8 | Image,
9 | TouchableOpacity,
10 | } from 'react-native';
11 | import { colors } from '../../styles/colors';
12 | import { inputStyles } from '../../styles/input';
13 |
14 | const DropdownSelectedItemsView = ({
15 | placeholder,
16 | error,
17 | labelsOfSelectedItems,
18 | openModal,
19 | isMultiple,
20 | selectedItem,
21 | selectedItems,
22 | dropdownIcon,
23 | dropdownStyle,
24 | dropdownIconStyle,
25 | selectedItemStyle,
26 | placeholderStyle,
27 | multipleSelectedItemStyle,
28 | dropdownErrorStyle,
29 | primaryColor,
30 | disabled,
31 | setIndexOfSelectedItem,
32 | }: any) => {
33 | const openActions = (label: string) => {
34 | openModal();
35 | setIndexOfSelectedItem(label); // immediately scrolls to list item with the specified label when modal
36 | };
37 | return (
38 | openModal()}
40 | style={({ pressed }) => [
41 | pressed && {
42 | ...inputStyles.inputFocusState,
43 | borderColor: primaryColor,
44 | },
45 | { ...inputStyles.input, ...dropdownStyle },
46 | error && //this must be last
47 | error !== '' &&
48 | !pressed && {
49 | ...inputStyles.inputFocusErrorState,
50 | ...dropdownErrorStyle,
51 | },
52 | ]}
53 | disabled={disabled}
54 | aria-disabled={disabled}
55 | testID="react-native-input-select-dropdown-input-container"
56 | >
57 |
62 | true}
65 | >
66 | {isMultiple ? (
67 | labelsOfSelectedItems?.map((label: string, i: Number) => (
68 | openActions(label)}
70 | key={`react-native-input-select-list-item-${Math.random()}-${i}`}
71 | style={[
72 | styles.selectedItems,
73 | { backgroundColor: primaryColor },
74 | multipleSelectedItemStyle,
75 | ]}
76 | label={label}
77 | disabled={disabled}
78 | />
79 | ))
80 | ) : (
81 | openActions(labelsOfSelectedItems)}
83 | style={[styles.blackText, selectedItemStyle]}
84 | label={labelsOfSelectedItems}
85 | disabled={disabled}
86 | />
87 | )}
88 | {selectedItem === '' && selectedItems?.length === 0 && (
89 | openModal()}
91 | style={[styles.blackText, placeholderStyle]}
92 | label={placeholder ?? 'Select an option'}
93 | disabled={disabled}
94 | />
95 | )}
96 |
97 |
98 |
99 | {dropdownIcon || (
100 |
101 | )}
102 |
103 |
104 | );
105 | };
106 |
107 | const DropdownContent = ({ onPress, style, label, ...rest }: any) => {
108 | return (
109 | onPress()} {...rest}>
110 | {label}
111 |
112 | );
113 | };
114 |
115 | const styles = StyleSheet.create({
116 | iconStyle: { position: 'absolute', right: 25, top: 25 },
117 | selectedItemsContainer: {
118 | flexDirection: 'row',
119 | flexWrap: 'nowrap',
120 | alignItems: 'center',
121 | },
122 | selectedItems: {
123 | color: colors.white,
124 | paddingHorizontal: 10,
125 | paddingVertical: 5,
126 | borderRadius: 10,
127 | backgroundColor: colors.primary,
128 | marginRight: 10,
129 | overflow: 'hidden',
130 | },
131 | blackText: { color: colors.black },
132 | });
133 |
134 | export default DropdownSelectedItemsView;
135 |
--------------------------------------------------------------------------------
/src/components/Input/index.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import {
3 | TextInput,
4 | StyleSheet,
5 | View,
6 | Platform,
7 | TextInputProps,
8 | ViewStyle,
9 | ColorValue,
10 | } from 'react-native';
11 | import { inputStyles } from '../../styles/input';
12 |
13 | export const Input = ({
14 | placeholder,
15 | value,
16 | onChangeText,
17 | style,
18 | primaryColor,
19 | textInputContainerStyle,
20 | ...rest
21 | }: {
22 | primaryColor?: ColorValue;
23 | textInputContainerStyle?: ViewStyle;
24 | } & TextInputProps) => {
25 | const [isFocused, setFocus] = useState(false);
26 |
27 | return (
28 |
29 | {
42 | setFocus(true);
43 | }}
44 | onBlur={() => setFocus(false)}
45 | value={value}
46 | onChangeText={onChangeText}
47 | returnKeyType="search"
48 | {...rest}
49 | />
50 |
51 | );
52 | };
53 |
54 | const styles = StyleSheet.create({
55 | container: { margin: 23 },
56 | });
57 |
58 | export default Input;
59 |
--------------------------------------------------------------------------------
/src/components/List/DropdownFlatList.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react-native/no-inline-styles */
2 | import React, { useEffect, useRef } from 'react';
3 | import { FlatList, FlatListProps, StyleSheet } from 'react-native';
4 | import DropdownListItem from '../Dropdown/DropdownListItem';
5 | import { ItemSeparatorComponent, ListEmptyComponent } from '../Others';
6 | import { TFlatList } from '../../types/index.types';
7 |
8 | const DropdownFlatList = ({
9 | options,
10 | optionLabel,
11 | optionValue,
12 | isMultiple,
13 | isSearchable,
14 | selectedItems,
15 | selectedItem,
16 | handleMultipleSelections,
17 | handleSingleSelection,
18 | primaryColor,
19 | checkboxControls,
20 | listComponentStyles,
21 | listIndex,
22 | emptyListMessage,
23 | listEmptyComponent,
24 | ...rest
25 | }: any & FlatListProps) => {
26 | const flatlistRef = useRef>(null);
27 |
28 | const scrollToItem = (index: number) => {
29 | flatlistRef?.current?.scrollToIndex({
30 | index,
31 | animated: true,
32 | });
33 | };
34 |
35 | useEffect(() => {
36 | if (listIndex.itemIndex >= 0) {
37 | scrollToItem(listIndex.itemIndex);
38 | }
39 | }, [listIndex]);
40 |
41 | const itemSeparator = () => (
42 |
45 | );
46 |
47 | return (
48 |
61 | )
62 | }
63 | contentContainerStyle={[
64 | isSearchable ? { paddingTop: 0 } : styles.contentContainerStyle,
65 | ]}
66 | ItemSeparatorComponent={itemSeparator}
67 | renderItem={(item) =>
68 | _renderItem(item, {
69 | optionLabel,
70 | optionValue,
71 | isMultiple,
72 | selectedOption: isMultiple ? selectedItems : selectedItem,
73 | onChange: isMultiple
74 | ? handleMultipleSelections
75 | : handleSingleSelection,
76 | scrollToItem,
77 | primaryColor,
78 | checkboxControls,
79 | })
80 | }
81 | keyExtractor={(_item, index) => `Options${index}`}
82 | ref={flatlistRef}
83 | onScrollToIndexFailed={({ index }) => {
84 | setTimeout(() => {
85 | scrollToItem(index);
86 | }, 500);
87 | }}
88 | {...rest}
89 | />
90 | );
91 | };
92 |
93 | const _renderItem = ({ item }: any, props: any) => {
94 | return (
95 |
106 | );
107 | };
108 |
109 | const styles = StyleSheet.create({
110 | contentContainerStyle: { paddingTop: 20 },
111 | });
112 |
113 | export default DropdownFlatList;
114 |
--------------------------------------------------------------------------------
/src/components/List/DropdownSectionList.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react-native/no-inline-styles */
2 | import React, { useEffect, useState, useRef } from 'react';
3 | import { SectionList, StyleSheet } from 'react-native';
4 | import DropdownListItem from '../Dropdown/DropdownListItem';
5 | import {
6 | ItemSeparatorComponent,
7 | ListEmptyComponent,
8 | SectionHeaderTitle,
9 | } from '../Others';
10 | import { extractPropertyFromArray } from '../../utils';
11 | import { TSectionList } from '../../types/index.types';
12 |
13 | const DropdownSectionList = ({
14 | options,
15 | optionLabel,
16 | optionValue,
17 | isMultiple,
18 | isSearchable,
19 | selectedItems,
20 | selectedItem,
21 | handleMultipleSelections,
22 | handleSingleSelection,
23 | primaryColor,
24 | checkboxControls,
25 | listComponentStyles,
26 | listIndex,
27 | emptyListMessage,
28 | listEmptyComponent,
29 | ...rest
30 | }: any) => {
31 | const [expandedSections, setExpandedSections] = useState(new Set());
32 |
33 | /**
34 | * Expand all sections
35 | */
36 | useEffect(() => {
37 | let initialState = new Set(extractPropertyFromArray(options, 'title'));
38 | setExpandedSections(initialState);
39 | }, [options]);
40 |
41 | /**
42 | * @param title
43 | */
44 | const handleToggleListExpansion = (title: string) => {
45 | setExpandedSections((expandedSectionsState) => {
46 | // Using Set here but you can use an array too
47 | const next = new Set(expandedSectionsState);
48 | if (next.has(title)) {
49 | next.delete(title);
50 | } else {
51 | next.add(title);
52 | }
53 | return next;
54 | });
55 | };
56 |
57 | /**
58 | * @description Scroll to item location
59 | */
60 |
61 | const sectionlistRef = useRef>(null);
62 |
63 | const scrollToLocation = (index: any) => {
64 | sectionlistRef?.current?.scrollToLocation({
65 | sectionIndex: index.sectionIndex,
66 | animated: true,
67 | itemIndex: index.itemIndex,
68 | });
69 | };
70 |
71 | useEffect(() => {
72 | if (listIndex.itemIndex >= 0 && listIndex.sectionIndex >= 0) {
73 | scrollToLocation(listIndex);
74 | }
75 | }, [listIndex]);
76 |
77 | const itemSeparator = () => (
78 |
81 | );
82 |
83 | return (
84 |
97 | )
98 | }
99 | contentContainerStyle={[
100 | isSearchable ? { paddingTop: 0 } : styles.contentContainerStyle,
101 | ]}
102 | ItemSeparatorComponent={itemSeparator}
103 | renderItem={(item) =>
104 | _renderItem(item, {
105 | optionLabel,
106 | optionValue,
107 | isMultiple,
108 | selectedOption: isMultiple ? selectedItems : selectedItem,
109 | onChange: isMultiple
110 | ? handleMultipleSelections
111 | : handleSingleSelection,
112 | primaryColor,
113 | checkboxControls,
114 | expandedSections,
115 | })
116 | }
117 | renderSectionHeader={({ section: { title } }) => (
118 | handleToggleListExpansion(title)}
122 | isExpanded={expandedSections.has(title)}
123 | />
124 | )}
125 | keyExtractor={(_item, index) => `Options${index}`}
126 | stickySectionHeadersEnabled={false}
127 | ref={sectionlistRef}
128 | onScrollToIndexFailed={() => {
129 | setTimeout(() => {
130 | scrollToLocation(listIndex);
131 | }, 500);
132 | }}
133 | {...rest}
134 | />
135 | );
136 | };
137 |
138 | const _renderItem = ({ section: { title }, item }: any, props: any) => {
139 | const isExpanded = props?.expandedSections.has(title);
140 |
141 | //return null if it is not expanded
142 | if (!isExpanded) return null;
143 |
144 | return (
145 |
155 | );
156 | };
157 |
158 | const styles = StyleSheet.create({
159 | contentContainerStyle: { paddingTop: 20 },
160 | });
161 |
162 | export default DropdownSectionList;
163 |
--------------------------------------------------------------------------------
/src/components/Others/index.tsx:
--------------------------------------------------------------------------------
1 | import React, { ReactNode } from 'react';
2 | import {
3 | View,
4 | Text,
5 | StyleSheet,
6 | TouchableOpacity,
7 | TextStyle,
8 | Image,
9 | ViewStyle,
10 | } from 'react-native';
11 | import { colors } from '../../styles/colors';
12 |
13 | export const ListEmptyComponent = ({
14 | listEmptyComponentStyle,
15 | emptyListMessage,
16 | }: any) => {
17 | return (
18 |
19 |
20 | {emptyListMessage || 'No options available'}
21 |
22 |
23 | );
24 | };
25 |
26 | export const ItemSeparatorComponent = ({
27 | itemSeparatorStyle,
28 | }: {
29 | itemSeparatorStyle: ViewStyle;
30 | }) => {
31 | return ;
32 | };
33 |
34 | export const ListItemContainer = ({
35 | children,
36 | listItemContainerStyle,
37 | }: {
38 | children: ReactNode;
39 | listItemContainerStyle: ViewStyle;
40 | }) => {
41 | return (
42 |
43 | {children}
44 |
45 | );
46 | };
47 |
48 | export const SectionHeaderTitle = ({
49 | title,
50 | sectionHeaderStyle,
51 | onPress,
52 | isExpanded,
53 | }: {
54 | title: string;
55 | sectionHeaderStyle?: TextStyle;
56 | onPress?: () => void;
57 | isExpanded: Boolean;
58 | }) => {
59 | return (
60 |
61 |
62 |
63 | {title}
64 |
65 |
66 |
67 |
68 |
69 |
70 | );
71 | };
72 |
73 | const styles = StyleSheet.create({
74 | listEmptyComponentStyle: {
75 | alignItems: 'center',
76 | width: '100%',
77 | marginVertical: 20,
78 | },
79 | itemSeparatorStyle: {
80 | backgroundColor: colors.gray,
81 | height: 1,
82 | opacity: 0.15,
83 | },
84 | listItemContainerStyle: {
85 | paddingHorizontal: 20,
86 | paddingVertical: 10,
87 | flexDirection: 'row',
88 | alignItems: 'center',
89 | },
90 | sectionHeaderStyle: { fontWeight: '500' },
91 | accordionStyle: {
92 | flexDirection: 'row',
93 | flexWrap: 'nowrap',
94 | justifyContent: 'space-between',
95 | alignContent: 'center',
96 | },
97 | rotatedIcon90: {
98 | transform: [{ rotate: '-90deg' }],
99 | },
100 | });
101 |
--------------------------------------------------------------------------------
/src/constants/index.ts:
--------------------------------------------------------------------------------
1 | export const DEFAULT_OPTION_LABEL = 'label';
2 | export const DEFAULT_OPTION_VALUE = 'value';
3 | export const CHECKBOX_SIZE = 14;
4 |
--------------------------------------------------------------------------------
/src/hooks/index.ts:
--------------------------------------------------------------------------------
1 | export * from './use-search';
2 | export * from './use-selection-handler';
3 | export * from './use-index-of-selected-item';
4 | export * from './use-modal';
5 | export * from './use-select-all';
6 |
--------------------------------------------------------------------------------
/src/hooks/use-index-of-selected-item.ts:
--------------------------------------------------------------------------------
1 | import { useState, useCallback } from 'react';
2 | import type { TFlatListItem, TSectionListItem } from '../types/index.types';
3 |
4 | interface UseIndexOfSelectedItemProps {
5 | options: (TFlatListItem | TSectionListItem)[];
6 | optionLabel: string;
7 | isSectionList: boolean;
8 | }
9 |
10 | /**
11 | *
12 | * @description for scrollToIndex in Sectionlist and Flatlist
13 | */
14 |
15 | export const useIndexOfSelectedItem = ({
16 | options,
17 | optionLabel,
18 | isSectionList,
19 | }: UseIndexOfSelectedItemProps) => {
20 | const [listIndex, setListIndex] = useState<{
21 | sectionIndex?: number;
22 | itemIndex: number;
23 | }>({ itemIndex: -1, sectionIndex: -1 });
24 |
25 | const setIndexOfSelectedItem = useCallback(
26 | (selectedLabel: string) => {
27 | if (isSectionList) {
28 | (options as TSectionListItem[]).forEach((section, sectionIndex) => {
29 | const itemIndex = section.data.findIndex(
30 | (item) => item[optionLabel] === selectedLabel
31 | );
32 | if (itemIndex !== -1) {
33 | setListIndex({ sectionIndex, itemIndex });
34 | }
35 | });
36 | } else {
37 | const itemIndex = (options as TFlatListItem[]).findIndex(
38 | (item) => item[optionLabel] === selectedLabel
39 | );
40 | if (itemIndex !== -1) {
41 | setListIndex({ itemIndex });
42 | }
43 | }
44 | },
45 | [options, optionLabel, isSectionList]
46 | );
47 |
48 | return { listIndex, setListIndex, setIndexOfSelectedItem };
49 | };
50 |
--------------------------------------------------------------------------------
/src/hooks/use-modal.ts:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { Platform } from 'react-native';
3 | import { TCustomModalControls } from '../types/index.types';
4 |
5 | interface UseModalProps {
6 | resetOptionsRelatedState: () => void;
7 | disabled?: boolean;
8 | modalControls?: TCustomModalControls;
9 | }
10 |
11 | export const useModal = ({
12 | resetOptionsRelatedState,
13 | disabled,
14 | modalControls,
15 | }: UseModalProps) => {
16 | const [isVisible, setIsVisible] = useState(false);
17 |
18 | const openModal = () => {
19 | if (disabled) return;
20 | setIsVisible(true);
21 | resetOptionsRelatedState();
22 | };
23 |
24 | const closeModal = () => {
25 | setIsVisible(false);
26 | resetOptionsRelatedState();
27 |
28 | // iOS supports the onDismiss prop but android does not, so we do this explicitly here
29 | // https://reactnative.dev/docs/modal#ondismiss-ios
30 | if (Platform.OS === 'android') {
31 | modalControls?.modalProps?.onDismiss?.();
32 | }
33 | };
34 |
35 | return {
36 | isVisible,
37 | openModal: () => openModal(),
38 | closeModal: () => closeModal(),
39 | };
40 | };
41 |
--------------------------------------------------------------------------------
/src/hooks/use-search.ts:
--------------------------------------------------------------------------------
1 | import { useState, useCallback, useEffect } from 'react';
2 | import type {
3 | TFlatList,
4 | TSectionList,
5 | TFlatListItem,
6 | TSectionListItem,
7 | } from '../types/index.types';
8 | import { escapeRegExp, isSectionList } from '../utils';
9 |
10 | interface UseSearchProps {
11 | initialOptions: TFlatList | TSectionList;
12 | optionLabel: string;
13 | optionValue: string;
14 | searchCallback: (value: string) => void;
15 | }
16 |
17 | export const useSearch = ({
18 | initialOptions,
19 | optionLabel,
20 | optionValue,
21 | searchCallback,
22 | }: UseSearchProps) => {
23 | const [searchValue, setSearchValue] = useState('');
24 | const [filteredOptions, setFilteredOptions] = useState<
25 | TFlatList | TSectionList
26 | >(initialOptions);
27 |
28 | const resetOptionsToDefault = (options: TFlatList | TSectionList) => {
29 | setFilteredOptions(options);
30 | };
31 |
32 | useEffect(() => {
33 | resetOptionsToDefault(initialOptions);
34 | return () => {};
35 | }, [initialOptions]);
36 |
37 | const searchFlatList = useCallback(
38 | (flatList: TFlatList, regexFilter: RegExp) => {
39 | return flatList.filter((item: TFlatListItem) => {
40 | return (
41 | item[optionLabel]?.toString().toLowerCase().search(regexFilter) !==
42 | -1 ||
43 | item[optionValue]?.toString().toLowerCase().search(regexFilter) !== -1
44 | );
45 | });
46 | },
47 | [optionLabel, optionValue]
48 | );
49 |
50 | const searchSectionList = useCallback(
51 | (sectionList: TSectionList, regexFilter: RegExp) => {
52 | return sectionList.map((listItem: TSectionListItem) => {
53 | // A section list is the combination of several flat lists
54 | const filteredData = searchFlatList(listItem.data, regexFilter);
55 |
56 | return { ...listItem, data: filteredData };
57 | });
58 | },
59 | [searchFlatList]
60 | );
61 |
62 | const isSection = isSectionList(initialOptions);
63 |
64 | const onSearch = useCallback(
65 | (value: string) => {
66 | searchCallback?.(value);
67 |
68 | const searchText = escapeRegExp(value).toLowerCase().trim();
69 | const regexFilter = new RegExp(searchText, 'i');
70 |
71 | const searchResults = isSection
72 | ? searchSectionList(initialOptions as TSectionList, regexFilter)
73 | : searchFlatList(initialOptions as TFlatList, regexFilter);
74 |
75 | setFilteredOptions(searchResults);
76 | },
77 | [
78 | initialOptions,
79 | isSection,
80 | searchCallback,
81 | searchFlatList,
82 | searchSectionList,
83 | ]
84 | );
85 |
86 | useEffect(() => {
87 | if (searchValue) {
88 | onSearch(searchValue);
89 | } else {
90 | resetOptionsToDefault(initialOptions);
91 | }
92 | }, [initialOptions, onSearch, searchValue]);
93 |
94 | return {
95 | searchValue,
96 | setSearchValue,
97 | filteredOptions,
98 | setFilteredOptions,
99 | isSectionList: isSection,
100 | };
101 | };
102 |
--------------------------------------------------------------------------------
/src/hooks/use-select-all.ts:
--------------------------------------------------------------------------------
1 | import { useCallback, useEffect, useState } from 'react';
2 | import { TFlatListItem, TSelectedItem } from '../types/index.types';
3 | import { removeDisabledItems } from '../utils';
4 |
5 | interface UseCheckSelectAllProps {
6 | options: TFlatListItem[];
7 | selectedItems: TSelectedItem[];
8 | isMultiple: boolean;
9 | onValueChange: (selectedValues: TSelectedItem[]) => void;
10 | listControls?: {
11 | selectAllCallback?: () => void;
12 | unselectAllCallback?: () => void;
13 | };
14 | optionValue: string;
15 | }
16 |
17 | export const useSelectAll = ({
18 | options,
19 | selectedItems,
20 | isMultiple,
21 | onValueChange,
22 | listControls,
23 | optionValue,
24 | }: UseCheckSelectAllProps) => {
25 | const [selectAll, setSelectAll] = useState(false);
26 |
27 | /**
28 | * @description Handle "Select All" logic
29 | */
30 | const handleSelectAll = useCallback(() => {
31 | setSelectAll((prevVal) => {
32 | let selectedValues: TSelectedItem[] = [];
33 |
34 | // Remove disabled items from selection
35 | const filteredOptions = removeDisabledItems(options);
36 |
37 | // if everything has not been selected, select all the values in the list
38 | if (!prevVal) {
39 | selectedValues = filteredOptions.map(
40 | (obj) => obj[optionValue]
41 | ) as TSelectedItem[];
42 | }
43 |
44 | onValueChange(selectedValues); // Send selected values to parent
45 | return !prevVal;
46 | });
47 |
48 | if (typeof listControls?.selectAllCallback === 'function' && !selectAll) {
49 | listControls.selectAllCallback();
50 | }
51 |
52 | if (typeof listControls?.unselectAllCallback === 'function' && selectAll) {
53 | listControls.unselectAllCallback();
54 | }
55 | }, [options, optionValue, listControls, selectAll, onValueChange]);
56 |
57 | /**
58 | * Check if all items are selected
59 | */
60 | const checkSelectAll = useCallback(() => {
61 | if (removeDisabledItems(options)?.length === selectedItems?.length) {
62 | setSelectAll(true);
63 | } else {
64 | setSelectAll(false);
65 | }
66 | }, [options, selectedItems]);
67 |
68 | /**
69 | * if the user decides to select the options one by one, this hook
70 | * runs to check if everything has been selected so that the `selectAll checkbox` can be selected
71 | */
72 | useEffect(() => {
73 | if (isMultiple) {
74 | checkSelectAll();
75 | }
76 | }, [checkSelectAll, isMultiple, selectedItems]);
77 |
78 | return { selectAll, handleSelectAll };
79 | };
80 |
--------------------------------------------------------------------------------
/src/hooks/use-selection-handler.ts:
--------------------------------------------------------------------------------
1 | import { useState, useCallback } from 'react';
2 | import { TSelectedItem } from '../types/index.types';
3 |
4 | interface UseSelectionHandlerProps {
5 | initialSelectedValue: TSelectedItem | TSelectedItem[]; // Can be a single value or an array
6 | isMultiple: boolean;
7 | maxSelectableItems?: number;
8 | onValueChange: (selectedItems: TSelectedItem | TSelectedItem[]) => void;
9 | closeModal: () => void;
10 | autoCloseOnSelect: boolean;
11 | }
12 |
13 | export const useSelectionHandler = ({
14 | initialSelectedValue,
15 | isMultiple,
16 | maxSelectableItems,
17 | onValueChange,
18 | closeModal,
19 | autoCloseOnSelect,
20 | }: UseSelectionHandlerProps) => {
21 | // Initialize state based on whether it's multiple selection or not
22 | const [selectedItem, setSelectedItem] = useState(
23 | isMultiple ? '' : (initialSelectedValue as TSelectedItem)
24 | );
25 | const [selectedItems, setSelectedItems] = useState(
26 | isMultiple ? (initialSelectedValue as TSelectedItem[]) : []
27 | );
28 |
29 | const handleSingleSelection = useCallback(
30 | (value: TSelectedItem) => {
31 | if (selectedItem === value) {
32 | setSelectedItem('');
33 | onValueChange(''); // Send null to parent when deselected
34 | } else {
35 | setSelectedItem(value);
36 | onValueChange(value); // Send selected value to parent
37 |
38 | if (autoCloseOnSelect) {
39 | closeModal(); // close modal upon selection
40 | }
41 | }
42 | },
43 | [selectedItem, onValueChange, autoCloseOnSelect, closeModal]
44 | );
45 |
46 | const handleMultipleSelections = useCallback(
47 | (value: TSelectedItem) => {
48 | setSelectedItems((prevVal) => {
49 | let selectedValues = [...prevVal];
50 |
51 | if (selectedValues.includes(value)) {
52 | // Remove item
53 | selectedValues = selectedValues.filter((item) => item !== value);
54 | } else {
55 | // Add item
56 | if (
57 | maxSelectableItems &&
58 | selectedValues.length >= maxSelectableItems
59 | ) {
60 | return selectedValues;
61 | }
62 | selectedValues.push(value);
63 | }
64 |
65 | onValueChange(selectedValues); // Send selected values to parent
66 | return selectedValues;
67 | });
68 | },
69 | [maxSelectableItems, onValueChange]
70 | );
71 |
72 | // Return the relevant state and handlers
73 | return {
74 | selectedItem,
75 | selectedItems,
76 | handleSingleSelection,
77 | handleMultipleSelections,
78 | setSelectedItems, // Expose for potential manual control
79 | setSelectedItem, // Expose for potential manual control
80 | };
81 | };
82 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React, {
2 | forwardRef,
3 | useCallback,
4 | useEffect,
5 | useImperativeHandle,
6 | } from 'react';
7 | import { TouchableOpacity, StyleSheet, View } from 'react-native';
8 | import Input from './components/Input';
9 | import CheckBox from './components/CheckBox';
10 | import Dropdown from './components/Dropdown/Dropdown';
11 | import DropdownFlatList from './components/List/DropdownFlatList';
12 | import DropdownSectionList from './components/List/DropdownSectionList';
13 | import CustomModal from './components/CustomModal';
14 | import { colors } from './styles/colors';
15 | import { DEFAULT_OPTION_LABEL, DEFAULT_OPTION_VALUE } from './constants';
16 | import type {
17 | DropdownProps,
18 | DropdownSelectHandle,
19 | TSelectedItem,
20 | } from './types/index.types';
21 | import { extractPropertyFromArray, getLabelsOfSelectedItems } from './utils';
22 | import {
23 | useSelectionHandler,
24 | useModal,
25 | useSearch,
26 | useIndexOfSelectedItem,
27 | useSelectAll,
28 | } from './hooks';
29 |
30 | export const DropdownSelect = forwardRef(
31 | (
32 | {
33 | testID,
34 | placeholder,
35 | label,
36 | error,
37 | helperText,
38 | options,
39 | optionLabel = DEFAULT_OPTION_LABEL,
40 | optionValue = DEFAULT_OPTION_VALUE,
41 | onValueChange,
42 | isMultiple = false,
43 | selectedValue = isMultiple ? [] : '',
44 | isSearchable,
45 | dropdownIcon,
46 | labelStyle,
47 | placeholderStyle,
48 | dropdownStyle,
49 | dropdownIconStyle,
50 | dropdownContainerStyle,
51 | dropdownErrorStyle,
52 | dropdownErrorTextStyle,
53 | dropdownHelperTextStyle,
54 | selectedItemStyle,
55 | multipleSelectedItemStyle,
56 | primaryColor = colors.gray,
57 | disabled = false,
58 | listHeaderComponent,
59 | listFooterComponent,
60 | listComponentStyles,
61 | listEmptyComponent,
62 | listControls,
63 | searchControls,
64 | modalControls,
65 | checkboxControls,
66 | autoCloseOnSelect = true,
67 | maxSelectableItems,
68 | ...rest
69 | },
70 | ref
71 | ) => {
72 | /*===========================================
73 | * Expose the methods to the parent using
74 | * useImperativeHandle
75 | *==========================================*/
76 | useImperativeHandle(ref, () => ({
77 | open: () => openModal(),
78 | close: () => closeModal(),
79 | }));
80 |
81 | /*===========================================
82 | * Search
83 | *==========================================*/
84 | const {
85 | searchValue,
86 | setSearchValue,
87 | setFilteredOptions,
88 | filteredOptions,
89 | isSectionList,
90 | } = useSearch({
91 | initialOptions: options,
92 | optionLabel,
93 | optionValue,
94 | searchCallback: useCallback(
95 | (value) => searchControls?.searchCallback?.(value),
96 | [searchControls]
97 | ),
98 | });
99 |
100 | /*===========================================
101 | * setIndexOfSelectedItem - For ScrollToIndex
102 | *==========================================*/
103 | const { listIndex, setListIndex, setIndexOfSelectedItem } =
104 | useIndexOfSelectedItem({
105 | options,
106 | optionLabel,
107 | isSectionList,
108 | });
109 |
110 | /*===========================================
111 | * Reset component states
112 | *==========================================*/
113 | const resetOptionsRelatedState = useCallback(() => {
114 | setSearchValue('');
115 | setFilteredOptions(options);
116 | setListIndex({ itemIndex: -1, sectionIndex: -1 });
117 | }, [options, setFilteredOptions, setListIndex, setSearchValue]);
118 |
119 | /*===========================================
120 | * Modal
121 | *==========================================*/
122 | const { isVisible, openModal, closeModal } = useModal({
123 | resetOptionsRelatedState,
124 | disabled,
125 | modalControls,
126 | });
127 |
128 | /*===========================================
129 | * Single and multiple selection Hook
130 | *==========================================*/
131 | const {
132 | selectedItem,
133 | selectedItems,
134 | setSelectedItem,
135 | setSelectedItems,
136 | handleSingleSelection,
137 | handleMultipleSelections,
138 | } = useSelectionHandler({
139 | initialSelectedValue: selectedValue,
140 | isMultiple,
141 | maxSelectableItems,
142 | onValueChange,
143 | closeModal: () => closeModal(),
144 | autoCloseOnSelect,
145 | });
146 |
147 | useEffect(() => {
148 | isMultiple
149 | ? setSelectedItems(selectedValue as TSelectedItem[])
150 | : setSelectedItem(selectedValue as TSelectedItem);
151 |
152 | return () => {};
153 | }, [
154 | selectedValue,
155 | setSelectedItems,
156 | setSelectedItem,
157 | isMultiple,
158 | onValueChange,
159 | ]);
160 |
161 | /*===========================================
162 | * List type
163 | *==========================================*/
164 | const ListTypeComponent = isSectionList
165 | ? DropdownSectionList
166 | : DropdownFlatList;
167 | const modifiedSectionData = extractPropertyFromArray(
168 | filteredOptions,
169 | 'data'
170 | )?.flat();
171 |
172 | /**
173 | * `options` is the original array, it never changes. (Do not use except you really need the original array) .
174 | * `filteredOptions` is a copy of options but can be mutated by `setFilteredOptions`, as a result, the value may change.
175 | * `modifiedOptions` should only be used for computations. It has the same structure for both `FlatList` and `SectionList`
176 | */
177 | const modifiedOptions = isSectionList
178 | ? modifiedSectionData
179 | : filteredOptions;
180 |
181 | /*===========================================
182 | * Select all Hook
183 | *==========================================*/
184 | const { selectAll, handleSelectAll } = useSelectAll({
185 | options: modifiedOptions,
186 | selectedItems,
187 | isMultiple,
188 | onValueChange,
189 | listControls,
190 | optionValue,
191 | });
192 |
193 | return (
194 | <>
195 | openModal()}
212 | closeModal={() => closeModal()}
213 | labelStyle={labelStyle}
214 | dropdownIcon={dropdownIcon}
215 | dropdownStyle={dropdownStyle}
216 | dropdownIconStyle={dropdownIconStyle}
217 | dropdownContainerStyle={dropdownContainerStyle}
218 | dropdownErrorStyle={dropdownErrorStyle}
219 | dropdownErrorTextStyle={dropdownErrorTextStyle}
220 | dropdownHelperTextStyle={dropdownHelperTextStyle}
221 | selectedItemStyle={selectedItemStyle}
222 | multipleSelectedItemStyle={multipleSelectedItemStyle}
223 | isMultiple={isMultiple}
224 | primaryColor={primaryColor}
225 | disabled={disabled}
226 | placeholderStyle={placeholderStyle}
227 | setIndexOfSelectedItem={setIndexOfSelectedItem}
228 | {...rest}
229 | />
230 | closeModal()}
233 | modalControls={modalControls}
234 | >
235 |
238 | {isSearchable && (
239 | setSearchValue(text)}
242 | style={searchControls?.textInputStyle}
243 | primaryColor={primaryColor}
244 | textInputContainerStyle={
245 | searchControls?.textInputContainerStyle
246 | }
247 | placeholder={
248 | searchControls?.textInputProps?.placeholder || 'Search'
249 | }
250 | aria-label={
251 | searchControls?.textInputProps?.placeholder || 'Search'
252 | }
253 | {...searchControls?.textInputProps}
254 | />
255 | )}
256 | {listHeaderComponent}
257 | {!listControls?.hideSelectAll &&
258 | isMultiple &&
259 | modifiedOptions?.length > 1 && (
260 |
261 |
262 | handleSelectAll()}
270 | primaryColor={primaryColor}
271 | checkboxControls={checkboxControls}
272 | />
273 |
274 |
275 | )}
276 | >
277 | }
278 | ListFooterComponent={listFooterComponent}
279 | listComponentStyles={listComponentStyles}
280 | options={filteredOptions}
281 | optionLabel={optionLabel}
282 | optionValue={optionValue}
283 | isMultiple={isMultiple}
284 | isSearchable={isSearchable}
285 | selectedItems={selectedItems}
286 | selectedItem={selectedItem}
287 | handleMultipleSelections={handleMultipleSelections}
288 | handleSingleSelection={handleSingleSelection}
289 | primaryColor={primaryColor}
290 | checkboxControls={checkboxControls}
291 | listIndex={listIndex}
292 | listEmptyComponent={listEmptyComponent}
293 | emptyListMessage={listControls?.emptyListMessage}
294 | keyboardShouldPersistTaps={listControls?.keyboardShouldPersistTaps}
295 | />
296 |
297 | >
298 | );
299 | }
300 | );
301 | const styles = StyleSheet.create({
302 | optionsContainerStyle: {
303 | paddingHorizontal: 20,
304 | paddingVertical: 10,
305 | flexDirection: 'row',
306 | },
307 | });
308 |
309 | export default DropdownSelect;
310 |
--------------------------------------------------------------------------------
/src/styles/colors.ts:
--------------------------------------------------------------------------------
1 | export const colors: any = {
2 | primary: 'green',
3 | red: '#FA4169',
4 | black: '#000000',
5 | white: '#FFFFFF',
6 | dark: '#11142D',
7 | gray: '#808191',
8 | lightGray: '#F7F7F7',
9 | disabled: '#d3d3d3',
10 | };
11 |
--------------------------------------------------------------------------------
/src/styles/input.ts:
--------------------------------------------------------------------------------
1 | import { StyleSheet } from 'react-native';
2 | import { colors } from './colors';
3 |
4 | export const inputStyles: any = StyleSheet.create({
5 | input: {
6 | paddingVertical: 18,
7 | paddingHorizontal: 23,
8 | backgroundColor: colors.lightGray,
9 | borderRadius: 8,
10 | borderColor: colors.dark,
11 | borderWidth: 1,
12 | color: colors.dark,
13 | width: '100%',
14 | minHeight: 64,
15 | },
16 | inputFocusErrorState: {
17 | borderWidth: 2,
18 | borderStyle: 'solid',
19 | borderColor: colors.red,
20 | },
21 | inputFocusState: {
22 | borderWidth: 2,
23 | borderStyle: 'solid',
24 | borderColor: colors.primary,
25 | },
26 | });
27 |
--------------------------------------------------------------------------------
/src/styles/typography.ts:
--------------------------------------------------------------------------------
1 | import { StyleSheet } from 'react-native';
2 |
3 | export const typography: any = StyleSheet.create({
4 | caption: {
5 | fontStyle: 'normal',
6 | fontWeight: 'normal',
7 | fontSize: 12,
8 | lineHeight: 15,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------
/src/types/index.types.ts:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import type {
3 | ViewStyle,
4 | ColorValue,
5 | TextStyle,
6 | ModalProps,
7 | TextInputProps,
8 | } from 'react-native';
9 |
10 | export type DropdownProps = CommonDropdownProps &
11 | TDropdownInputProps &
12 | TControls &
13 | TListProps;
14 |
15 | export type CommonDropdownProps = {
16 | testID?: string;
17 | label?: string;
18 | options: TFlatList | TSectionList;
19 | optionLabel?: string;
20 | optionValue?: string;
21 | onValueChange: (selectedItems: TSelectedItem | TSelectedItem[]) => void;
22 | selectedValue: TSelectedItem | TSelectedItem[];
23 | autoCloseOnSelect?: boolean;
24 | maxSelectableItems?: number;
25 | };
26 |
27 | export type TDropdownInputProps = {
28 | placeholder?: string;
29 | error?: string;
30 | helperText?: string;
31 | isMultiple?: boolean;
32 | isSearchable?: boolean;
33 | dropdownIcon?: React.ReactNode;
34 | labelStyle?: TextStyle;
35 | dropdownStyle?: ViewStyle;
36 | dropdownIconStyle?: ViewStyle;
37 | dropdownContainerStyle?: ViewStyle;
38 | dropdownErrorStyle?: ViewStyle;
39 | dropdownErrorTextStyle?: TextStyle;
40 | dropdownHelperTextStyle?: TextStyle;
41 | selectedItemStyle?: TextStyle;
42 | multipleSelectedItemStyle?: TextStyle;
43 | primaryColor?: ColorValue;
44 | disabled?: boolean;
45 | placeholderStyle?: TextStyle;
46 | };
47 |
48 | type TControls = {
49 | searchControls?: TSearchControls;
50 | checkboxControls?: TCheckboxControls;
51 | modalControls?: TCustomModalControls;
52 | listControls?: TListControls;
53 | };
54 |
55 | type TSearchControls = {
56 | textInputStyle?: ViewStyle | TextStyle;
57 | textInputContainerStyle?: ViewStyle;
58 | textInputProps?: TextInputProps;
59 | searchCallback?: (value: string) => void;
60 | };
61 |
62 | export type TCheckboxControls = {
63 | checkboxSize?: number;
64 | checkboxStyle?: ViewStyle;
65 | checkboxLabelStyle?: TextStyle;
66 | checkboxComponent?: React.ReactNode;
67 | checkboxDisabledStyle?: ViewStyle;
68 | checkboxUnselectedColor?: ColorValue;
69 | };
70 |
71 | export type TCustomModalControls = {
72 | modalBackgroundStyle?: ViewStyle;
73 | modalOptionsContainerStyle?: ViewStyle;
74 | modalProps?: ModalProps;
75 | };
76 |
77 | export type TListProps = {
78 | listHeaderComponent?: React.ReactNode;
79 | listFooterComponent?: React.ReactNode;
80 | listComponentStyles?: {
81 | listEmptyComponentStyle?: TextStyle;
82 | itemSeparatorStyle?: ViewStyle;
83 | sectionHeaderStyle?: TextStyle;
84 | };
85 | listEmptyComponent?: React.ReactNode;
86 | };
87 |
88 | type TListControls = {
89 | selectAllText?: string;
90 | unselectAllText?: string;
91 | selectAllCallback?: () => void;
92 | unselectAllCallback?: () => void;
93 | hideSelectAll?: boolean;
94 | emptyListMessage?: string;
95 | keyboardShouldPersistTaps?: 'always' | 'never' | 'handled';
96 | };
97 |
98 | export type TSelectedItem = string | number | boolean | undefined;
99 | export type TSelectedItemWithReactComponent =
100 | | TSelectedItem
101 | | React.ReactElement;
102 |
103 | export type TFlatList = TFlatListItem[];
104 | export type TFlatListItem = {
105 | [key: string]: TSelectedItemWithReactComponent;
106 | };
107 |
108 | export type TSectionList = TSectionListItem[];
109 | export type TSectionListItem = { title: string; data: TFlatList };
110 |
111 | export interface DropdownSelectHandle {
112 | open: () => void;
113 | close: () => void;
114 | }
115 |
--------------------------------------------------------------------------------
/src/utils/index.ts:
--------------------------------------------------------------------------------
1 | import { TSelectedItem } from '../types/index.types';
2 | import {
3 | TFlatList,
4 | TFlatListItem,
5 | TSectionList,
6 | TSelectedItemWithReactComponent,
7 | } from '../types/index.types';
8 |
9 | export const extractPropertyFromArray = (arr: any[], property: string) => {
10 | let extractedValue = arr?.map((item: any) => item[property]);
11 |
12 | return extractedValue;
13 | };
14 |
15 | export const escapeRegExp = (text: string) => {
16 | return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
17 | };
18 |
19 | export const removeDisabledItems = (items: TFlatList) => {
20 | return items?.filter((item: TFlatListItem) => !item.disabled);
21 | };
22 |
23 | export const isSectionList = (options: TFlatList | TSectionList): boolean => {
24 | return (options as TSectionList).some(
25 | (item) => item.title && item.data && Array.isArray(item.data)
26 | );
27 | };
28 |
29 | /**
30 | *
31 | * @description get the labels of the items that were selected from the options array for either multiple or single selections
32 | * @returns
33 | */
34 | export const getLabelsOfSelectedItems = ({
35 | isMultiple,
36 | optionLabel,
37 | optionValue,
38 | selectedItem,
39 | selectedItems,
40 | modifiedOptions,
41 | }: {
42 | isMultiple: boolean;
43 | optionLabel: string;
44 | optionValue: string;
45 | selectedItem: TSelectedItem;
46 | selectedItems: TSelectedItem[];
47 | modifiedOptions: TFlatList;
48 | }) => {
49 | // Multiple select
50 | if (isMultiple && Array.isArray(selectedItems)) {
51 | let selectedLabels: TSelectedItemWithReactComponent[] = [];
52 |
53 | selectedItems?.forEach((element: TSelectedItem) => {
54 | let selectedItemLabel = modifiedOptions?.find(
55 | (item: TFlatListItem) => item[optionValue] === element
56 | )?.[optionLabel];
57 |
58 | if (selectedItemLabel !== '') {
59 | selectedLabels.push(selectedItemLabel);
60 | }
61 | });
62 | return selectedLabels;
63 | }
64 |
65 | // Single select
66 | let selectedItemLabel = modifiedOptions?.find(
67 | (item: TFlatListItem) => item[optionValue] === selectedItem
68 | );
69 | return selectedItemLabel?.[optionLabel];
70 | };
71 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "extends": "./tsconfig",
4 | "exclude": ["example"]
5 | }
6 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./",
4 | "paths": {
5 | "react-native-input-select": ["./src/index"],
6 | "react": ["./node_modules/@types/react"]
7 | },
8 | "allowUnreachableCode": false,
9 | "allowUnusedLabels": false,
10 | "esModuleInterop": true,
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext"],
14 | "module": "esnext",
15 | "moduleResolution": "node",
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "target": "esnext"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------