Expo Barcode Scanner

Aniket Jha
Nov 8 · 2 min read

Before we start we will update our node, npm and expo cli. Just to use all the latest features. Now create a new expo project. Choose the project with everything previously setup. We choose this app to get quickly started.

nvm use 12 // install version 12 - latest@2019
npm install -g expo-cli // install expo cli globally
expo init // create a project
// choose the javascript project with navigation setup
Final product demo

Scanner Screen

In the app, as I am using the minimal setup project I am using the default HomeScreen as ScannerScreen. We are using a React class component you may simply use functional components with hooks for state management.

The Scanner screen is a class-based component. The state has two important properties one hasCameraPermissions for if the screen has permission to access the camera and the second property isisScanned for if something has been scanned or not. Initially, the state of ScannerScreen for hasCameraPermissions is null. Null means that we are requesting for permission. And state isScanned is false means nothing is scanned as of now.

As the scanner requires camera permission thus we need to ask for camera permission from the user.
Permission is an asynchronous task and we must ask for permission as soon as this component is mounted so componentDidMount seems like a good place to start. Note Permission asking is asynchronous so we have to make componentDidMount a async function. If Camera permission is given then hasCameraPermissions is set to true and we may successfully render our barcode scanner and open camera else if permission is declined hasCameraPermissions is set to false and we render declined permission message.

Next, we have a function for handling a successfully scanned barcode. If the bar code is scanned this function will be called. Our function handleBarCodeScanned is passed as callback to onBarCodeScanned prop on BarCodeScanner component. In handleBarCodeScanned function we receive a scan object as an argument which has two important properties, one is the type which means what type of bar code was scanned and the other is data which is the encrypted data in our barcode. We will destructure these properties as others are irrelevant to us. In our case of handleBarCodeScanned function, we are just navigating to the DecodeScreen passing code data as params. The DecodeScreen then displays the data.

Github Repo: Branch bar-code-scanner

Aniket Jha

Written by

Full Stack Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade