This post is all about implementing the QR Code Scanner in your cool new react-native application. In this post, you will learn
- How to implement
QRCode Scanner
in our app. - How to read data from the QR Code in React-Native app.
- How to open a link in the browser after successfully reading data from the QR Code.
Before start, first you will need a React-Native app to start with, hence you can follow how to create a react-native app for beginners and start after that from here.
Complete source code of this tutorial is available here — RNQRCodeScanning.
What is React-Native
React Native is a JavaScript framework for writing real, natively rendering mobile applications for iOS and Android. It’s based on React, Facebook’s JavaScript library for building user interfaces, but instead of targeting the browser, it targets mobile platforms. In other words: web developers can now write mobile applications that look and feel truly “native,” all from the comfort of a JavaScript library that we already know and love. Plus, because most of the code you write can be shared between platforms, React Native makes it easy to simultaneously develop for both Android and iOS.
Similar to React for the Web, React Native applications are written using a mixture of JavaScript and XML-Esque markup, known as JSX. Then, under the hood, the React Native “bridge” invokes the native rendering APIs in Objective-C (for iOS) or Java (for Android). Thus, your application will render using real mobile UI components, not web views, and will look and feel like any other mobile application. React Native also exposes JavaScript interfaces for platform APIs, so your React Native apps can access platform features like the phone camera, or the user’s location.
React Native currently supports both iOS and Android and has the potential to expand to future platforms as well. In this tutorial, we’ll cover QR Code implementation. The vast majority of the code we write will be cross-platform. And yes: you can use React Native to build production-ready mobile applications! Some anecdota: Facebook, Palantir, and TaskRabbit are already using it in production for user-facing applications.
The fact that React Native actually renders using its host platform’s standard rendering APIs enables it to stand out from most existing methods of cross-platform application development, like Cordova or Ionic.
Existing methods of writing mobile applications using combinations of JavaScript, HTML, and CSS typically render using web views. While this approach can work, it also comes with drawbacks, especially around performance. Additionally, they do not usually have access to the host platform’s set of native UI elements. When these frameworks do try to mimic native UI elements, the results usually “feel” just a little off; reverse-engineering all the fine details of things like animations takes an enormous amount of effort, and they can quickly become out of date.
What and why QR Code?
QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed in 1994 for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.
QR code scanning is something almost every smartphone user has done at least once. We scan QR codes in supermarkets, on products in general, and oh, Amazon delivery! It’s a very handy way to recognize products instead of entering 16 digit long ID numbers etc. Similarly, reading ID numbers from Passports, etc could be very handy if you are an international hotel owner and require guests to carry passports as IDs. Or maybe you want to read off a vehicle registration number using your phone.
Here are some potential use cases for these plugins in React-Native app
- Online Payment apps — QR scanners can provide product info to users and paying the facility.
- Delivery app — QR Code scan can track/sign off a package and you can pay them by scanning QR Code
- Quick access to offers — Scan QR codes and go to a webpage
- Web authentication of a mobile app — Similar to Whatsapp Web
- Event app — Scan tickets or events passes
…… and many more
All this can now be done in React-Native apps, with the latest open source react-native-qrcode-scanner npm package available in React-Native. In this article, we will focus on such implementation. So here are some of the scan plugins and functionalities you can implement with React-native.
- react-native-qrcode-scanner
- react-native-scan-view
- react-native-camera
….and many more.
Step 1:- Install the react-native-camera plugin by executing this command
yarn add react-native-camera@git+https://git@github.com/react-native-community/react-native-camera.git
Here react-native-camera is a dependency for this package so you will need to add it in your project.
Step 2:- Install the QR Scanner plugin by executing this command
yarn add react-native-qrcode-scanner
Now, to use react-native-qrcode-scanner, import
the react-native-qrcode-scanner
module and use the <QRCodeScanner />
tag.
Here, we are working on react-native version 0.60.5. Hence we don’t need to link any package externally as in the latest versions above 0.60 react-native provides auto-linking functionality.
Add Button to scan a QRCode and to get the result
Now you are ready to use the QR Code Scanner function provided by the React-Native react-native-qrcode-scanner
package and get the result. Before this let us make a beautiful view to access the QRCode function by clicking a button and getting the data in response.
The Result for the above code is:
As we have completed our UI for beautiful interaction, you can simply use the below function to complete a QR Code scan process.
Complete UI and Logic of the application —
In this tutorial, we have used react-native default Linking property to open the external URL in the browser only when we get a URL after a successful scan. If the result contains a URL then it will navigate to that web page or if it does not contain any URL then it will print the result in both cases.
onSuccess = (e) => {
const check = e.data.substring(0, 4);
console.log('scanned data' + check);
this.setState({
result: e,
scan: false,
ScanResult: true
})
if (check === 'http')
{
Linking
.openURL(e.data)
.catch(err => console.error('An error occured', err));
} else {
this.setState({
result: e,
scan: false,
ScanResult: true})}}
On clicking the “Click to Scan” button it will initiate the hardware camera and a pop up will appear for camera permission. To set the camera permission you would need to add the following code to the AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
By adding this line in your AndroidManifest.xml
you are all set to use camera feature in your application to scan a QR Code.
Let’s scan some QR Codes…
If you are scanning a webpage QR code then on successful scan it will return a URL and in this tutorial we have written a function for that, if it does contain a URL then it will print the result and navigate to the web page in the browser and if it is not an encoded web page QR Code then it will simply print the result and you will see a button below the result to scan another QR Code.
Here in the scanning view, you can see we have two buttons at the bottom of the app which are —
- Ok. Got it
- Stop Scan
Here in the first case, it will call the reactivate() function where this will reactivate the scanning ability of the component. And in the second case, it will just close the camera and navigate back to the home page.
Let’s check the results —
This will open the scanned webpage in the browser.
There are some methods that you can use to get features according to your requirement —
reactivate()
Call this method to programmatically enabling scanning again. Use this by attaching a ref
like so <QRCodeScanner ref={(node) => { this.scanner = node }}>
and calling this.scanner.reactivate()
Props
onRead
(required)
propType: func.isRequired
default: (e) => (console.log('QR code scanned!', e))
Will call this specified method when a QR code or a barcode is detected in the camera’s view passing in the event emitted upon reading the code.
fadeIn
propType: bool
default: true
When set to true
this ensures that the camera view fades in after the initial load up instead of being rendered immediately. Set this to false to prevent the animated fade in of the camera view.
reactivate
propType: bool
default: false
When set to false
, when a QR code is scanned, the QRCodeScanner
will not scan another code until it is re-rendered. When set to true
this will reactivate the scanning ability of the component.
reactivateTimeout
propType: number
default: 0
Use this to configure how long it should take before the QRCodeScanner
should reactivate.
topContent
propType: oneOfType([ PropTypes.element, PropTypes.string, ])
Use this to render any additional content at the top of the camera view.
bottomContent
propType: oneOfType([ PropTypes.element, PropTypes.string, ])
Use this to render any additional content at the bottom of the camera view.
containerStyle
propType: any
Use this to pass styling for the outermost container. Useful for adding margin/padding to account for navigation bar.
cameraStyle
propType: any
Use this to pass or overwrite styling for the camera window rendered.
topViewStyle
propType: any
Use this to pass or overwrite styling for the <View>
that contains the topContent
prop.
bottomViewStyle
propType: any
Use this to pass or overwrite styling for the <View>
that contains the bottomContent
prop.
showMarker
propType: boolean
default: false
Use this to show marker on the camera scanning window.
customMarker
propType: element
Pass a RN element/component to use it as a custom marker.
markerStyle
propType: any
Use this to add custom styling to the default marker.
notAuthorizedView
propType: element
Pass a RN element/component to use it when no permissions given to the camera (iOS only).
cameraType
propType: oneOf(['front', 'back'])
default: 'back'
Use this to control which camera to use for scanning QR codes, defaults to rear camera.
checkAndroid6Permissions
propType: bool
default: false
Use this to enable permission checking on Android 6
permissionDialogTitle
propType: string
default: 'Info'
Use this to setting permission dialog title (Android only).
permissionDialogMessage
propType: string
default: 'Need camera permission'
Use this to setting permission dialog message (Android only).
cameraProps
propType: object
Properties to be passed to the Camera
component.
Using this npm package you can scan a Barcode too. I have not tried that in here but why don’t you give it a try and tell me in the comment section below.
Here in the tutorial, successfully implemented the plugin and got the perfect result. You can follow all the steps and achieve this very easily or you can clone my repo on Github for both the plugins here and enjoy 😎 😎 😎 🕺 🕺 🕺..…
Conclusion
In this post, we learned how to integrate the QR Code scanner and use it in React-Native applications. Since the plugin is amazingly light and have great documentation, it is the developers’ first choice when it comes to creating QR code.
Complete source code of this tutorial is available here — RNQRCodeScanning.
Next Steps
Now that you have learned the implementation of react-native-qrcode-scanner in React-Native, you can also try
- Firebase — Integrate Firebase | Analytics | Push notifications | Firebase CRUD
- How To in React Native — Geolocation | Life cycle hooks | Image Picker | Redux implementation | Make API calls | Navigation | Translation | Send & Read SMS | Google Vision
- Payments — Apple Pay | Stripe payments
- Authentication — Google Login| Facebook login | Twitter login | Phone Auth | Anonymous Login
- Create Instagram / Whatsapp Story Feature in React Native
- React Native life cycle hooks | Implement Redux | Async actions with Redux
- Create Awesome Apps in React Native using Full App
If you need a base to start your next React Native app, you can make your next awesome app using React Native Full App
Top comments (0)