├── .circleci └── config.yml ├── .editorconfig ├── .gitattributes ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── example ├── app.json ├── assets │ ├── adaptive-icon.png │ ├── favicon.png │ ├── icon.png │ └── splash.png ├── babel.config.js ├── index.js ├── metro.config.js ├── package.json ├── src │ ├── App.tsx │ └── SegmentedControl.tsx ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── package.json ├── scripts └── bootstrap.js ├── src ├── __tests__ │ └── index.test.tsx └── index.tsx ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | default: 5 | docker: 6 | - image: circleci/node:10 7 | working_directory: ~/project 8 | 9 | commands: 10 | attach_project: 11 | steps: 12 | - attach_workspace: 13 | at: ~/project 14 | 15 | jobs: 16 | install-dependencies: 17 | executor: default 18 | steps: 19 | - checkout 20 | - attach_project 21 | - restore_cache: 22 | keys: 23 | - dependencies-{{ checksum "package.json" }} 24 | - dependencies- 25 | - restore_cache: 26 | keys: 27 | - dependencies-example-{{ checksum "example/package.json" }} 28 | - dependencies-example- 29 | - run: 30 | name: Install dependencies 31 | command: | 32 | yarn install --cwd example --frozen-lockfile 33 | yarn install --frozen-lockfile 34 | - save_cache: 35 | key: dependencies-{{ checksum "package.json" }} 36 | paths: node_modules 37 | - save_cache: 38 | key: dependencies-example-{{ checksum "example/package.json" }} 39 | paths: example/node_modules 40 | - persist_to_workspace: 41 | root: . 42 | paths: . 43 | 44 | lint: 45 | executor: default 46 | steps: 47 | - attach_project 48 | - run: 49 | name: Lint files 50 | command: | 51 | yarn lint 52 | 53 | typescript: 54 | executor: default 55 | steps: 56 | - attach_project 57 | - run: 58 | name: Typecheck files 59 | command: | 60 | yarn typescript 61 | 62 | unit-tests: 63 | executor: default 64 | steps: 65 | - attach_project 66 | - run: 67 | name: Run unit tests 68 | command: | 69 | yarn test --coverage 70 | - store_artifacts: 71 | path: coverage 72 | destination: coverage 73 | 74 | build-package: 75 | executor: default 76 | steps: 77 | - attach_project 78 | - run: 79 | name: Build package 80 | command: | 81 | yarn prepare 82 | 83 | workflows: 84 | build-and-test: 85 | jobs: 86 | - install-dependencies 87 | - lint: 88 | requires: 89 | - install-dependencies 90 | - typescript: 91 | requires: 92 | - install-dependencies 93 | - unit-tests: 94 | requires: 95 | - install-dependencies 96 | - build-package: 97 | requires: 98 | - install-dependencies 99 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | .idea 35 | .gradle 36 | local.properties 37 | android.iml 38 | 39 | # Cocoapods 40 | # 41 | example/ios/Pods 42 | 43 | # node.js 44 | # 45 | node_modules/ 46 | npm-debug.log 47 | yarn-debug.log 48 | yarn-error.log 49 | 50 | # BUCK 51 | buck-out/ 52 | \.buckd/ 53 | android/app/libs 54 | android/keystores/debug.keystore 55 | 56 | # Expo 57 | .expo/* 58 | 59 | # generated by bob 60 | lib/ 61 | -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | # Override Yarn command so we can automatically setup the repo on running `yarn` 2 | 3 | yarn-path "scripts/bootstrap.js" 4 | -------------------------------------------------------------------------------- /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 start the packager: 18 | 19 | ```sh 20 | yarn example start 21 | ``` 22 | 23 | To run the example app on Android: 24 | 25 | ```sh 26 | yarn example android 27 | ``` 28 | 29 | To run the example app on iOS: 30 | 31 | ```sh 32 | yarn example ios 33 | ``` 34 | 35 | To run the example app on Web: 36 | 37 | ```sh 38 | yarn example web 39 | ``` 40 | 41 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 42 | 43 | ```sh 44 | yarn typescript 45 | yarn lint 46 | ``` 47 | 48 | To fix formatting errors, run the following: 49 | 50 | ```sh 51 | yarn lint --fix 52 | ``` 53 | 54 | Remember to add tests for your change if possible. Run the unit tests by: 55 | 56 | ```sh 57 | yarn test 58 | ``` 59 | 60 | ### Commit message convention 61 | 62 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 63 | 64 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 65 | - `feat`: new features, e.g. add new method to the module. 66 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 67 | - `docs`: changes into documentation, e.g. add usage example for the module.. 68 | - `test`: adding or updating tests, e.g. add integration tests using detox. 69 | - `chore`: tooling changes, e.g. change CI config. 70 | 71 | Our pre-commit hooks verify that your commit message matches this format when committing. 72 | 73 | ### Linting and tests 74 | 75 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 76 | 77 | 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. 78 | 79 | Our pre-commit hooks verify that the linter and tests pass when committing. 80 | 81 | ### Publishing to npm 82 | 83 | 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. 84 | 85 | To publish new versions, run the following: 86 | 87 | ```sh 88 | yarn release 89 | ``` 90 | 91 | ### Scripts 92 | 93 | The `package.json` file contains various scripts for common tasks: 94 | 95 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 96 | - `yarn typescript`: type-check files with TypeScript. 97 | - `yarn lint`: lint files with ESLint. 98 | - `yarn test`: run unit tests with Jest. 99 | - `yarn example start`: start the Metro server for the example app. 100 | - `yarn example android`: run the example app on Android. 101 | - `yarn example ios`: run the example app on iOS. 102 | 103 | ### Sending a pull request 104 | 105 | > **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://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). 106 | 107 | When you're sending a pull request: 108 | 109 | - Prefer small pull requests focused on one change. 110 | - Verify that linters and tests are passing. 111 | - Review the documentation to make sure it looks good. 112 | - Follow the pull request template when opening a pull request. 113 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 114 | 115 | ## Code of Conduct 116 | 117 | ### Our Pledge 118 | 119 | 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. 120 | 121 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 122 | 123 | ### Our Standards 124 | 125 | Examples of behavior that contributes to a positive environment for our community include: 126 | 127 | - Demonstrating empathy and kindness toward other people 128 | - Being respectful of differing opinions, viewpoints, and experiences 129 | - Giving and gracefully accepting constructive feedback 130 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 131 | - Focusing on what is best not just for us as individuals, but for the overall community 132 | 133 | Examples of unacceptable behavior include: 134 | 135 | - The use of sexualized language or imagery, and sexual attention or 136 | advances of any kind 137 | - Trolling, insulting or derogatory comments, and personal or political attacks 138 | - Public or private harassment 139 | - Publishing others' private information, such as a physical or email 140 | address, without their explicit permission 141 | - Other conduct which could reasonably be considered inappropriate in a 142 | professional setting 143 | 144 | ### Enforcement Responsibilities 145 | 146 | 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. 147 | 148 | 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. 149 | 150 | ### Scope 151 | 152 | 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. 153 | 154 | ### Enforcement 155 | 156 | 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. 157 | 158 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 159 | 160 | ### Enforcement Guidelines 161 | 162 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 163 | 164 | #### 1. Correction 165 | 166 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 167 | 168 | **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. 169 | 170 | #### 2. Warning 171 | 172 | **Community Impact**: A violation through a single incident or series of actions. 173 | 174 | **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. 175 | 176 | #### 3. Temporary Ban 177 | 178 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 179 | 180 | **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. 181 | 182 | #### 4. Permanent Ban 183 | 184 | **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. 185 | 186 | **Consequence**: A permanent ban from any sort of public interaction within the community. 187 | 188 | ### Attribution 189 | 190 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 191 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 192 | 193 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 194 | 195 | [homepage]: https://www.contributor-covenant.org 196 | 197 | For answers to common questions about this code of conduct, see the FAQ at 198 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Karthik-B-06 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

React Native Segmented Control

3 | 4 | ![npm](https://badgen.net/badge/license/MIT/blue) 5 | [![npm](https://badgen.net/npm/dt/rn-segmented-control)](https://www.npmjs.com/package/rn-segmented-control) 6 | [![npm](https://badgen.net/npm/v/rn-segmented-control)](https://www.npmjs.com/package/rn-segmented-control) 7 | [![](https://badgen.net/npm/types/tslib)](https://badgen.net/npm/types/tslib) 8 | 9 | ![SegmentedControl](https://user-images.githubusercontent.com/35562287/149650171-3cd9c972-6cf5-4aef-989f-199820d5b0e6.gif) 10 | React Native Segmented Control for both iOS, Android and Web 😎 11 | 12 |
13 | 14 | ## :anchor: Installation 15 | 16 | ```sh 17 | npm install rn-segmented-control 18 | ``` 19 | 20 | ```sh 21 | yarn add rn-segmented-control 22 | ``` 23 | 24 | ## :arrows_counterclockwise: Dependencies 25 | 26 | Make sure you have [React Native Reanimated](https://docs.swmansion.com/react-native-reanimated/docs) and [React Native Gesture Handler](https://docs.swmansion.com/react-native-gesture-handler/docs/) installed and configured. 27 | 28 | ## :wrench: Props 29 | 30 | | Name | Description | Required | Type | Default | 31 | | ----------------------- | ---------------------------------------------- | -------- | --------- | -------- | 32 | | segments | An array of labels for segments | YES | Array | [] | 33 | | currentIndex | Index for the currently active segment | YES | Number | 0 | 34 | | onChange | A callback Function with pressed segment index | YES | Function | () => {} | 35 | | badgeValues | An array of badge value for segments. | NO | Array | [] | 36 | | isRTL | Controls the toggle animation direction | NO | Boolean | false | 37 | | containerMargin | The value used to determine the width | NO | Number | 16 | 38 | | activeTextStyle | active text styles | NO | TextStyle | {} | 39 | | inactiveTextStyle | inactive text styles. | NO | TextStyle | {} | 40 | | segmentedControlWrapper | Style object for the Segmented Control. | NO | ViewStyle | {} | 41 | | pressableWrapper | Style object for the Pressable Container | NO | ViewStyle | {} | 42 | | tileStyle | Style object for the Absolute positioned tile | NO | ViewStyle | {} | 43 | | activeBadgeStyle | Active Badge Style | NO | ViewStyle | {} | 44 | | inactiveBadgeStyle | Inactive Badge Style | NO | ViewStyle | {} | 45 | | badgeTextStyle | Badge text styles | NO | TextStyle | {} | 46 | 47 | > :warning: all View styles or Text Styles passed as props overrides some default styles provided by the package. Make sure you use it properly :) 48 | 49 | > :information_source: To apply your own `shadowStyles` use the tileStyle prop 50 | 51 | ## :mag: Usage 52 | 53 | ```tsx 54 | import SegmentedControl from 'rn-segmented-control'; 55 | 56 | import * as React from 'react'; 57 | import { StyleSheet, View } from 'react-native'; 58 | import SegmentedControl from './SegmentedControl'; 59 | 60 | export default function App() { 61 | const [tabIndex, setTabIndex] = React.useState(0); 62 | 63 | return ( 64 | 65 | 66 | setTabIndex(index)} 70 | currentIndex={tabIndex} 71 | /> 72 | 73 | 74 | ); 75 | } 76 | 77 | const styles = StyleSheet.create({ 78 | container: { 79 | flex: 1, 80 | justifyContent: 'center', 81 | }, 82 | box: { 83 | marginHorizontal: 16, 84 | marginVertical: 16, 85 | }, 86 | }); 87 | ``` 88 | 89 | ### Working Examples 90 | 91 | Check the expo example app [here](https://github.com/Karthik-B-06/react-native-segmented-control/tree/main/example). 92 | 93 | ## :iphone: iOS and Android working Example. 94 | 95 | ![SegmentedControl](https://user-images.githubusercontent.com/35562287/149624111-2b3d1f7f-a685-404a-a167-f7020706880d.gif) 96 | 97 | ## :desktop_computer: Web 98 | 99 | ![DesktopExample](https://user-images.githubusercontent.com/35562287/149624298-c415d1cc-5f65-4e44-8efb-02a9e0f96dbb.gif) 100 | 101 | ## :v: Contributing 102 | 103 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 104 | 105 | ## :man: Author 106 | 107 | [Karthik B](https://twitter.com/_iam_karthik) 108 | 109 | ## :clipboard: License 110 | 111 | MIT 112 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | plugins: ['react-native-reanimated/plugin'], 4 | }; 5 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-segmented-control-example", 3 | "displayName": "SegmentedControl Example", 4 | "expo": { 5 | "name": "react-native-segmented-control-example", 6 | "slug": "react-native-segmented-control-example", 7 | "description": "Example app for react-native-segmented-control", 8 | "privacy": "public", 9 | "version": "1.0.0", 10 | "platforms": [ 11 | "ios", 12 | "android", 13 | "web" 14 | ], 15 | "ios": { 16 | "supportsTablet": true 17 | }, 18 | "assetBundlePatterns": [ 19 | "**/*" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /example/assets/adaptive-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Karthik-B-06/react-native-segmented-control/65041ee19443ec1c9f1ba7e73f7387207f11cb83/example/assets/adaptive-icon.png -------------------------------------------------------------------------------- /example/assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Karthik-B-06/react-native-segmented-control/65041ee19443ec1c9f1ba7e73f7387207f11cb83/example/assets/favicon.png -------------------------------------------------------------------------------- /example/assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Karthik-B-06/react-native-segmented-control/65041ee19443ec1c9f1ba7e73f7387207f11cb83/example/assets/icon.png -------------------------------------------------------------------------------- /example/assets/splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Karthik-B-06/react-native-segmented-control/65041ee19443ec1c9f1ba7e73f7387207f11cb83/example/assets/splash.png -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = function (api) { 5 | api.cache(true); 6 | 7 | return { 8 | presets: ['babel-preset-expo'], 9 | plugins: [ 10 | [ 11 | 'module-resolver', 12 | { 13 | extensions: ['.tsx', '.ts', '.js', '.json'], 14 | alias: { 15 | // For development, we want to alias the library to the source 16 | [pak.name]: path.join(__dirname, '..', pak.source), 17 | }, 18 | }, 19 | ], 20 | 'react-native-reanimated/plugin', 21 | ], 22 | }; 23 | }; 24 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import 'react-native-gesture-handler'; 2 | import { registerRootComponent } from 'expo'; 3 | 4 | import App from './src/App'; 5 | 6 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App); 7 | // It also ensures that whether you load the app in the Expo client or in a native build, 8 | // the environment is set up appropriately 9 | registerRootComponent(App); 10 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const blacklist = require('metro-config/src/defaults/blacklist'); 3 | const escape = require('escape-string-regexp'); 4 | const pak = require('../package.json'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | module.exports = { 13 | projectRoot: __dirname, 14 | watchFolders: [root], 15 | 16 | // We need to make sure that only one version is loaded for peerDependencies 17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules 18 | resolver: { 19 | blacklistRE: blacklist( 20 | modules.map( 21 | (m) => 22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 23 | ) 24 | ), 25 | 26 | extraNodeModules: modules.reduce((acc, name) => { 27 | acc[name] = path.join(__dirname, 'node_modules', name); 28 | return acc; 29 | }, {}), 30 | }, 31 | 32 | transformer: { 33 | getTransformOptions: async () => ({ 34 | transform: { 35 | experimentalImportSupport: false, 36 | inlineRequires: true, 37 | }, 38 | }), 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-segmented-control-example", 3 | "description": "Example app for react-native-segmented-control", 4 | "version": "0.0.1", 5 | "private": true, 6 | "main": "index", 7 | "scripts": { 8 | "android": "expo start --android", 9 | "ios": "expo start --ios", 10 | "web": "expo start --web", 11 | "start": "expo start", 12 | "test": "jest" 13 | }, 14 | "dependencies": { 15 | "@types/react-native": "^0.66.12", 16 | "babel-loader": "^8.2.3", 17 | "expo": "^44.0.5", 18 | "expo-splash-screen": "~0.14.1", 19 | "react": "17.0.2", 20 | "react-dom": "17.0.2", 21 | "react-native": "0.64.3", 22 | "react-native-gesture-handler": "~2.1.0", 23 | "react-native-reanimated": "~2.3.1", 24 | "react-native-unimodules": "~0.15.0", 25 | "react-native-web": "~0.17.5", 26 | "rn-segmented-control": "^1.1.0" 27 | }, 28 | "devDependencies": { 29 | "@babel/core": "~7.12.10", 30 | "@babel/runtime": "^7.9.6", 31 | "babel-plugin-module-resolver": "^4.0.0", 32 | "babel-preset-expo": "8.3.0", 33 | "expo-cli": "^4.0.13" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StyleSheet, View } from 'react-native'; 3 | import SegmentedControl from './SegmentedControl'; 4 | 5 | export default function App() { 6 | const [tabIndex, setTabIndex] = React.useState(0); 7 | const [tabIndex1, setTabIndex1] = React.useState(0); 8 | const [tabIndex2, setTabIndex2] = React.useState(0); 9 | const [tabIndex3, setTabIndex3] = React.useState(0); 10 | const [tabIndex4, setTabIndex4] = React.useState(0); 11 | const [tabIndex5, setTabIndex5] = React.useState(0); 12 | const [tabIndex6, setTabIndex6] = React.useState(0); 13 | 14 | return ( 15 | 16 | 17 | setTabIndex(index)} 21 | currentIndex={tabIndex} 22 | badgeValues={[2, null, 1]} 23 | /> 24 | 25 | 26 | setTabIndex1(index)} 30 | currentIndex={tabIndex1} 31 | /> 32 | 33 | 34 | setTabIndex2(index)} 38 | currentIndex={tabIndex2} 39 | /> 40 | 41 | 42 | setTabIndex3(index)} 46 | currentIndex={tabIndex3} 47 | segmentedControlWrapper={{ backgroundColor: '#4a5568' }} 48 | activeTextStyle={styles.customBlackColor} 49 | inactiveTextStyle={styles.customWhiteColor} 50 | /> 51 | 52 | 53 | setTabIndex4(index)} 57 | currentIndex={tabIndex4} 58 | segmentedControlWrapper={{ backgroundColor: '#a3e635' }} 59 | activeTextStyle={styles.customGreenColor} 60 | inactiveTextStyle={styles.customWhiteColor} 61 | /> 62 | 63 | 64 | setTabIndex5(index)} 68 | currentIndex={tabIndex5} 69 | segmentedControlWrapper={{ backgroundColor: '#7dd3fc' }} 70 | activeTextStyle={styles.customBlueTextColor} 71 | inactiveTextStyle={styles.customWhiteColor} 72 | tileStyle={styles.customBlueColor} 73 | badgeValues={[2]} 74 | activeBadgeStyle={styles.customBadgeBlueColor} 75 | /> 76 | 77 | 78 | setTabIndex6(index)} 82 | currentIndex={tabIndex6} 83 | badgeValues={[2, null, 1]} 84 | /> 85 | 86 | 87 | ); 88 | } 89 | 90 | const styles = StyleSheet.create({ 91 | container: { 92 | flex: 1, 93 | justifyContent: 'center', 94 | }, 95 | box: { 96 | marginHorizontal: 16, 97 | marginVertical: 16, 98 | }, 99 | customBlackColor: { 100 | color: 'black', 101 | }, 102 | customWhiteColor: { 103 | color: 'white', 104 | }, 105 | customGreenColor: { 106 | color: '#3f6212', 107 | }, 108 | customBlueColor: { 109 | backgroundColor: '#e0f2fe', 110 | }, 111 | customBlueTextColor: { 112 | color: '#0369a1', 113 | }, 114 | customBadgeBlueColor: { 115 | backgroundColor: '#38bdf8', 116 | }, 117 | }); 118 | -------------------------------------------------------------------------------- /example/src/SegmentedControl.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { 3 | Pressable, 4 | StyleSheet, 5 | Text, 6 | TextStyle, 7 | View, 8 | ViewStyle, 9 | } from 'react-native'; 10 | import Animated, { 11 | useAnimatedStyle, 12 | useSharedValue, 13 | withSpring, 14 | } from 'react-native-reanimated'; 15 | import { widthPercentageToDP } from 'react-native-responsive-screen'; 16 | 17 | interface SegmentedControlProps { 18 | /** 19 | * The Segments Text Array 20 | */ 21 | segments: Array; 22 | /** 23 | * The Current Active Segment Index 24 | */ 25 | currentIndex: number; 26 | /** 27 | * A callback onPress of a Segment 28 | */ 29 | onChange: (index: number) => void; 30 | /** 31 | * An array of Badge Values corresponding to the Segment 32 | */ 33 | badgeValues?: Array; 34 | /** 35 | * Is right-to-left mode. 36 | */ 37 | isRTL?: boolean; 38 | /** 39 | * The container margin for the segmented control 40 | * Used to calculate the width of Segmented Control 41 | */ 42 | containerMargin?: number; 43 | /** 44 | * Active Segment Text Style 45 | */ 46 | activeTextStyle?: TextStyle; 47 | /** 48 | * InActive Segment Text Style 49 | */ 50 | inactiveTextStyle?: TextStyle; 51 | /** 52 | * Segment Container Styles 53 | */ 54 | segmentedControlWrapper?: ViewStyle; 55 | /** 56 | * Pressable Container Styles 57 | */ 58 | pressableWrapper?: ViewStyle; 59 | /** 60 | * The moving Tile Container Styles 61 | */ 62 | tileStyle?: ViewStyle; 63 | /** 64 | * Active Badge Styles 65 | */ 66 | activeBadgeStyle?: ViewStyle; 67 | /** 68 | * Inactive Badge Styles 69 | */ 70 | inactiveBadgeStyle?: ViewStyle; 71 | /** 72 | * Badge Text Styles 73 | */ 74 | badgeTextStyle?: TextStyle; 75 | } 76 | 77 | const defaultShadowStyle = { 78 | shadowColor: '#000', 79 | shadowOffset: { 80 | width: 1, 81 | height: 1, 82 | }, 83 | shadowOpacity: 0.025, 84 | shadowRadius: 1, 85 | 86 | elevation: 1, 87 | }; 88 | 89 | const DEFAULT_SPRING_CONFIG = { 90 | stiffness: 150, 91 | damping: 20, 92 | mass: 1, 93 | overshootClamping: false, 94 | restSpeedThreshold: 0.001, 95 | restDisplacementThreshold: 0.001, 96 | }; 97 | 98 | const SegmentedControl: React.FC = ({ 99 | segments, 100 | currentIndex, 101 | onChange, 102 | badgeValues = [], 103 | isRTL = false, 104 | containerMargin = 0, 105 | activeTextStyle, 106 | inactiveTextStyle, 107 | segmentedControlWrapper, 108 | pressableWrapper, 109 | tileStyle, 110 | activeBadgeStyle, 111 | inactiveBadgeStyle, 112 | badgeTextStyle, 113 | }: SegmentedControlProps) => { 114 | const width = widthPercentageToDP('100%') - containerMargin * 2; 115 | const translateValue = width / segments.length; 116 | const tabTranslateValue = useSharedValue(0); 117 | 118 | // useCallBack with an empty array as input, which will call inner lambda only once and memoize the reference for future calls 119 | const memoizedTabPressCallback = React.useCallback( 120 | (index) => { 121 | onChange(index); 122 | }, 123 | [onChange] 124 | ); 125 | useEffect(() => { 126 | // If phone is set to RTL, make sure the animation does the correct transition. 127 | const transitionMultiplier = isRTL ? -1 : 1; 128 | tabTranslateValue.value = withSpring( 129 | currentIndex * (translateValue * transitionMultiplier), 130 | DEFAULT_SPRING_CONFIG 131 | ); 132 | // eslint-disable-next-line react-hooks/exhaustive-deps 133 | }, [currentIndex]); 134 | 135 | const tabTranslateAnimatedStyles = useAnimatedStyle(() => { 136 | return { 137 | transform: [{ translateX: tabTranslateValue.value }], 138 | }; 139 | }); 140 | 141 | const finalisedActiveTextStyle: TextStyle = { 142 | fontSize: 15, 143 | fontWeight: '600', 144 | textAlign: 'center', 145 | color: '#111827', 146 | ...activeTextStyle, 147 | }; 148 | 149 | const finalisedInActiveTextStyle: TextStyle = { 150 | fontSize: 15, 151 | textAlign: 'center', 152 | color: '#4b5563', 153 | ...inactiveTextStyle, 154 | }; 155 | 156 | const finalisedActiveBadgeStyle: ViewStyle = { 157 | backgroundColor: '#27272a', 158 | marginLeft: 4, 159 | alignItems: 'center', 160 | justifyContent: 'center', 161 | ...activeBadgeStyle, 162 | }; 163 | 164 | const finalisedInActiveBadgeStyle: ViewStyle = { 165 | backgroundColor: '#6b7280', 166 | marginLeft: 4, 167 | justifyContent: 'center', 168 | alignItems: 'center', 169 | ...inactiveBadgeStyle, 170 | }; 171 | 172 | const finalisedBadgeTextStyle: TextStyle = { 173 | fontSize: 11, 174 | fontWeight: '500', 175 | textAlign: 'center', 176 | color: '#FFFFFF', 177 | ...badgeTextStyle, 178 | }; 179 | 180 | return ( 181 | 184 | 196 | {segments.map((segment, index) => { 197 | return ( 198 | memoizedTabPressCallback(index)} 200 | key={index} 201 | style={[styles.touchableContainer, pressableWrapper]} 202 | > 203 | 204 | 211 | {segment} 212 | 213 | {badgeValues[index] && ( 214 | 222 | 223 | {badgeValues[index]} 224 | 225 | 226 | )} 227 | 228 | 229 | ); 230 | })} 231 | 232 | ); 233 | }; 234 | 235 | const styles = StyleSheet.create({ 236 | defaultSegmentedControlWrapper: { 237 | position: 'relative', 238 | display: 'flex', 239 | flexDirection: 'row', 240 | alignItems: 'center', 241 | borderRadius: 8, 242 | backgroundColor: '#f3f4f6', 243 | }, 244 | touchableContainer: { 245 | flex: 1, 246 | elevation: 9, 247 | paddingVertical: 12, 248 | }, 249 | textWrapper: { 250 | flexDirection: 'row', 251 | alignItems: 'center', 252 | justifyContent: 'center', 253 | }, 254 | movingSegmentStyle: { 255 | top: 0, 256 | marginVertical: 2, 257 | marginHorizontal: 2, 258 | borderRadius: 6, 259 | backgroundColor: '#FFFFFF', 260 | }, 261 | // Badge Styles 262 | defaultBadgeContainerStyle: { 263 | alignItems: 'center', 264 | justifyContent: 'center', 265 | height: 16, 266 | width: 16, 267 | borderRadius: 9999, 268 | alignContent: 'flex-end', 269 | }, 270 | }); 271 | 272 | export default SegmentedControl; 273 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "jsx": "react-native", 4 | "target": "esnext", 5 | "lib": [ 6 | "esnext" 7 | ], 8 | "allowJs": true, 9 | "skipLibCheck": true, 10 | "noEmit": true, 11 | "allowSyntheticDefaultImports": true, 12 | "resolveJsonModule": true, 13 | "esModuleInterop": true, 14 | "moduleResolution": "node" 15 | }, 16 | "extends": "expo/tsconfig.base" 17 | } 18 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const createExpoWebpackConfigAsync = require('@expo/webpack-config'); 3 | const { resolver } = require('./metro.config'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const node_modules = path.join(__dirname, 'node_modules'); 7 | 8 | module.exports = async function (env, argv) { 9 | const config = await createExpoWebpackConfigAsync(env, argv); 10 | 11 | config.module.rules.push({ 12 | test: /\.(js|jsx|ts|tsx)$/, 13 | include: path.resolve(root, 'src'), 14 | use: 'babel-loader', 15 | }); 16 | 17 | // We need to make sure that only one version is loaded for peerDependencies 18 | // So we alias them to the versions in example's node_modules 19 | Object.assign(config.resolve.alias, { 20 | ...resolver.extraNodeModules, 21 | 'react-native-web': path.join(node_modules, 'react-native-web'), 22 | }); 23 | 24 | return config; 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rn-segmented-control", 3 | "version": "1.1.2", 4 | "description": "A simple and customizable React Native component to have a segmented control", 5 | "main": "lib/commonjs/index.js", 6 | "module": "lib/module/index.js", 7 | "types": "lib/typescript/src/index.d.ts", 8 | "react-native": "src/index.tsx", 9 | "source": "src/index", 10 | "files": [ 11 | "src", 12 | "lib", 13 | "!**/__tests__", 14 | "!**/__fixtures__", 15 | "!**/__mocks__", 16 | "android", 17 | "ios", 18 | "cpp", 19 | "react-native-segmented-control.podspec", 20 | "!lib/typescript/example", 21 | "!android/build", 22 | "!ios/build" 23 | ], 24 | "scripts": { 25 | "test": "jest", 26 | "typescript": "tsc --noEmit", 27 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 28 | "prepare": "bob build", 29 | "release": "release-it", 30 | "example": "yarn --cwd example", 31 | "pods": "cd example && pod-install --quiet", 32 | "bootstrap": "yarn example && yarn && yarn pods" 33 | }, 34 | "keywords": [ 35 | "react-native", 36 | "react-component", 37 | "react-native-component", 38 | "react", 39 | "react native", 40 | "mobile", 41 | "ios", 42 | "android", 43 | "ui" 44 | ], 45 | "repository": "https://github.com/Karthik-B-06/react-native-segmented-control", 46 | "author": "Karthik-B-06 (https://github.com/Karthik-B-06)", 47 | "license": "MIT", 48 | "bugs": { 49 | "url": "https://github.com/Karthik-B-06/react-native-segmented-control/issues" 50 | }, 51 | "homepage": "https://github.com/Karthik-B-06/react-native-segmented-control#readme", 52 | "publishConfig": { 53 | "registry": "https://registry.npmjs.org/" 54 | }, 55 | "devDependencies": { 56 | "@commitlint/config-conventional": "^11.0.0", 57 | "@react-native-community/eslint-config": "^2.0.0", 58 | "@release-it/conventional-changelog": "^2.0.0", 59 | "@types/jest": "^26.0.0", 60 | "@types/react": "^16.9.19", 61 | "@types/react-native": "^0.66.12", 62 | "commitlint": "^11.0.0", 63 | "eslint": "^7.2.0", 64 | "eslint-config-prettier": "^7.0.0", 65 | "eslint-plugin-prettier": "^3.1.3", 66 | "husky": "^4.2.5", 67 | "jest": "^26.0.1", 68 | "pod-install": "^0.1.0", 69 | "prettier": "^2.0.5", 70 | "react": "16.13.1", 71 | "react-native": "0.63.4", 72 | "react-native-builder-bob": "^0.18.2", 73 | "release-it": "^14.2.2", 74 | "typescript": "^4.1.3" 75 | }, 76 | "peerDependencies": { 77 | "react": "*", 78 | "react-native": "*" 79 | }, 80 | "jest": { 81 | "preset": "react-native", 82 | "modulePathIgnorePatterns": [ 83 | "/example/node_modules", 84 | "/lib/" 85 | ] 86 | }, 87 | "husky": { 88 | "hooks": { 89 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", 90 | "pre-commit": "yarn lint && yarn typescript" 91 | } 92 | }, 93 | "commitlint": { 94 | "extends": [ 95 | "@commitlint/config-conventional" 96 | ] 97 | }, 98 | "release-it": { 99 | "git": { 100 | "commitMessage": "chore: release ${version}", 101 | "tagName": "v${version}" 102 | }, 103 | "npm": { 104 | "publish": true 105 | }, 106 | "github": { 107 | "release": true 108 | }, 109 | "plugins": { 110 | "@release-it/conventional-changelog": { 111 | "preset": "angular" 112 | } 113 | } 114 | }, 115 | "eslintConfig": { 116 | "root": true, 117 | "extends": [ 118 | "@react-native-community", 119 | "prettier" 120 | ], 121 | "rules": { 122 | "prettier/prettier": [ 123 | "error", 124 | { 125 | "quoteProps": "consistent", 126 | "singleQuote": true, 127 | "tabWidth": 2, 128 | "trailingComma": "es5", 129 | "useTabs": false 130 | } 131 | ] 132 | } 133 | }, 134 | "eslintIgnore": [ 135 | "node_modules/", 136 | "lib/" 137 | ], 138 | "prettier": { 139 | "quoteProps": "consistent", 140 | "singleQuote": true, 141 | "tabWidth": 2, 142 | "trailingComma": "es5", 143 | "useTabs": false 144 | }, 145 | "react-native-builder-bob": { 146 | "source": "src", 147 | "output": "lib", 148 | "targets": [ 149 | "commonjs", 150 | "module", 151 | "typescript" 152 | ] 153 | }, 154 | "dependencies": { 155 | "react-native-gesture-handler": "2.1.0", 156 | "react-native-reanimated": "2.3.1", 157 | "react-native-responsive-screen": "^1.4.2" 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const child_process = require('child_process'); 3 | 4 | const root = path.resolve(__dirname, '..'); 5 | const args = process.argv.slice(2); 6 | const options = { 7 | cwd: process.cwd(), 8 | env: process.env, 9 | stdio: 'inherit', 10 | encoding: 'utf-8', 11 | }; 12 | 13 | let result; 14 | 15 | if (process.cwd() !== root || args.length) { 16 | // We're not in the root of the project, or additional arguments were passed 17 | // In this case, forward the command to `yarn` 18 | result = child_process.spawnSync('yarn', args, options); 19 | } else { 20 | // If `yarn` is run without arguments, perform bootstrap 21 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 22 | } 23 | 24 | process.exitCode = result.status; 25 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { 3 | Pressable, 4 | StyleSheet, 5 | Text, 6 | TextStyle, 7 | View, 8 | ViewStyle, 9 | } from 'react-native'; 10 | import Animated, { 11 | useAnimatedStyle, 12 | useSharedValue, 13 | withSpring, 14 | } from 'react-native-reanimated'; 15 | import { widthPercentageToDP } from 'react-native-responsive-screen'; 16 | 17 | interface SegmentedControlProps { 18 | /** 19 | * The Segments Text Array 20 | */ 21 | segments: Array; 22 | /** 23 | * The Current Active Segment Index 24 | */ 25 | currentIndex: number; 26 | /** 27 | * A callback onPress of a Segment 28 | */ 29 | onChange: (index: number) => void; 30 | /** 31 | * An array of Badge Values corresponding to the Segment 32 | */ 33 | badgeValues?: Array; 34 | /** 35 | * Is right-to-left mode. 36 | */ 37 | isRTL?: boolean; 38 | /** 39 | * The container margin for the segmented control 40 | * Used to calculate the width of Segmented Control 41 | */ 42 | containerMargin?: number; 43 | /** 44 | * Active Segment Text Style 45 | */ 46 | activeTextStyle?: TextStyle; 47 | /** 48 | * InActive Segment Text Style 49 | */ 50 | inactiveTextStyle?: TextStyle; 51 | /** 52 | * Segment Container Styles 53 | */ 54 | segmentedControlWrapper?: ViewStyle; 55 | /** 56 | * Pressable Container Styles 57 | */ 58 | pressableWrapper?: ViewStyle; 59 | /** 60 | * The moving Tile Container Styles 61 | */ 62 | tileStyle?: ViewStyle; 63 | /** 64 | * Active Badge Styles 65 | */ 66 | activeBadgeStyle?: ViewStyle; 67 | /** 68 | * Inactive Badge Styles 69 | */ 70 | inactiveBadgeStyle?: ViewStyle; 71 | /** 72 | * Badge Text Styles 73 | */ 74 | badgeTextStyle?: TextStyle; 75 | } 76 | 77 | const defaultShadowStyle = { 78 | shadowColor: '#000', 79 | shadowOffset: { 80 | width: 1, 81 | height: 1, 82 | }, 83 | shadowOpacity: 0.025, 84 | shadowRadius: 1, 85 | 86 | elevation: 1, 87 | }; 88 | 89 | const DEFAULT_SPRING_CONFIG = { 90 | stiffness: 150, 91 | damping: 20, 92 | mass: 1, 93 | overshootClamping: false, 94 | restSpeedThreshold: 0.001, 95 | restDisplacementThreshold: 0.001, 96 | }; 97 | 98 | const SegmentedControl: React.FC = ({ 99 | segments, 100 | currentIndex, 101 | onChange, 102 | badgeValues = [], 103 | isRTL = false, 104 | containerMargin = 0, 105 | activeTextStyle, 106 | inactiveTextStyle, 107 | segmentedControlWrapper, 108 | pressableWrapper, 109 | tileStyle, 110 | activeBadgeStyle, 111 | inactiveBadgeStyle, 112 | badgeTextStyle, 113 | }: SegmentedControlProps) => { 114 | const width = widthPercentageToDP('100%') - containerMargin * 2; 115 | const translateValue = width / segments.length; 116 | const tabTranslateValue = useSharedValue(0); 117 | 118 | // useCallBack with an empty array as input, which will call inner lambda only once and memoize the reference for future calls 119 | const memoizedTabPressCallback = React.useCallback( 120 | (index) => { 121 | onChange(index); 122 | }, 123 | [onChange] 124 | ); 125 | useEffect(() => { 126 | // If phone is set to RTL, make sure the animation does the correct transition. 127 | const transitionMultiplier = isRTL ? -1 : 1; 128 | tabTranslateValue.value = withSpring( 129 | currentIndex * (translateValue * transitionMultiplier), 130 | DEFAULT_SPRING_CONFIG 131 | ); 132 | // eslint-disable-next-line react-hooks/exhaustive-deps 133 | }, [currentIndex]); 134 | 135 | const tabTranslateAnimatedStyles = useAnimatedStyle(() => { 136 | return { 137 | transform: [{ translateX: tabTranslateValue.value }], 138 | }; 139 | }); 140 | 141 | const finalisedActiveTextStyle: TextStyle = { 142 | fontSize: 15, 143 | fontWeight: '600', 144 | textAlign: 'center', 145 | color: '#111827', 146 | ...activeTextStyle, 147 | }; 148 | 149 | const finalisedInActiveTextStyle: TextStyle = { 150 | fontSize: 15, 151 | textAlign: 'center', 152 | color: '#4b5563', 153 | ...inactiveTextStyle, 154 | }; 155 | 156 | const finalisedActiveBadgeStyle: ViewStyle = { 157 | backgroundColor: '#27272a', 158 | marginLeft: 4, 159 | alignItems: 'center', 160 | justifyContent: 'center', 161 | ...activeBadgeStyle, 162 | }; 163 | 164 | const finalisedInActiveBadgeStyle: ViewStyle = { 165 | backgroundColor: '#6b7280', 166 | marginLeft: 4, 167 | justifyContent: 'center', 168 | alignItems: 'center', 169 | ...inactiveBadgeStyle, 170 | }; 171 | 172 | const finalisedBadgeTextStyle: TextStyle = { 173 | fontSize: 11, 174 | fontWeight: '500', 175 | textAlign: 'center', 176 | color: '#FFFFFF', 177 | ...badgeTextStyle, 178 | }; 179 | 180 | return ( 181 | 184 | 196 | {segments.map((segment, index) => { 197 | return ( 198 | memoizedTabPressCallback(index)} 200 | key={index} 201 | style={[styles.touchableContainer, pressableWrapper]} 202 | > 203 | 204 | 211 | {segment} 212 | 213 | {badgeValues[index] && ( 214 | 222 | 223 | {badgeValues[index]} 224 | 225 | 226 | )} 227 | 228 | 229 | ); 230 | })} 231 | 232 | ); 233 | }; 234 | 235 | const styles = StyleSheet.create({ 236 | defaultSegmentedControlWrapper: { 237 | position: 'relative', 238 | display: 'flex', 239 | flexDirection: 'row', 240 | alignItems: 'center', 241 | borderRadius: 8, 242 | backgroundColor: '#f3f4f6', 243 | }, 244 | touchableContainer: { 245 | flex: 1, 246 | elevation: 9, 247 | paddingVertical: 12, 248 | }, 249 | textWrapper: { 250 | flexDirection: 'row', 251 | alignItems: 'center', 252 | justifyContent: 'center', 253 | }, 254 | movingSegmentStyle: { 255 | top: 0, 256 | marginVertical: 2, 257 | marginHorizontal: 2, 258 | borderRadius: 6, 259 | backgroundColor: '#FFFFFF', 260 | }, 261 | // Badge Styles 262 | defaultBadgeContainerStyle: { 263 | alignItems: 'center', 264 | justifyContent: 'center', 265 | height: 16, 266 | width: 16, 267 | borderRadius: 9999, 268 | alignContent: 'flex-end', 269 | }, 270 | }); 271 | 272 | export default SegmentedControl; 273 | -------------------------------------------------------------------------------- /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-segmented-control": ["./src/index"] 6 | }, 7 | "allowUnreachableCode": false, 8 | "allowUnusedLabels": false, 9 | "esModuleInterop": true, 10 | "importsNotUsedAsValues": "error", 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 | --------------------------------------------------------------------------------