Home > Software design >  How to Open URL "on click" after Scanning a QR Code in React-Native Android App
How to Open URL "on click" after Scanning a QR Code in React-Native Android App

Time:04-05

I am new to React-Native & created a QR Scanner App. After scanning want to open url onClick/onPress.

Here is the image of my code

-- Here is the code

onSuccess = (e) => { setResult(e.data) setScan(false) }

// Start scanner startScan = () => { setScan(true) setResult() }

            <QRCodeScanner
              reactivate={true}
              showMarker={true}
              ref={(node) => { this.scanner = node }}
              onRead={this.onSuccess}
              topContent={
                <Text style={styles.centerText}>
                  Scan your QRCode!
                </Text>
              }
              bottomContent={
                <TouchableOpacity style={styles.buttonTouchable} onPress={() => setScan(false)}>
                  <Text style={styles.buttonText}>Cancel Scan</Text>
                </TouchableOpacity>
              }
            />

CodePudding user response:

Let me help you

Your code might look like this:

import { useState } from 'react';
import { Text } from 'react-native';

const App = () => {
  const [scan, setScan] = useState(false);
  const [result, setResult] = useState();

  function onSuccess(e){
    setResult(e.data);
    setScan(false);
  }

  function onURLPress(){
    Linking.openURL(result);
  }

  return (
    <QRCodeScanner
      reactivate={true}
      showMarker={true}
      ref={(node) => { this.scanner = node }}
      onRead={this.onSuccess}
      topContent={
        <Text style={styles.centerText}>
          Scan your QRCode!
        </Text>
      }
      bottomContent={
        <Text style={[styles.buttonText, styles.buttonTouchable]} onPress={() => setScan(false)}>Cancel Scan</Text>
      }
    />

    {/* This is where you show the generated url */}
    {result && <Text onPress={onURLPress}>{result}</Text>}
  )
}

Note that you can change your bottomContent Text to use onPress as well, instead of using TouchableOpacity.

  • Related