0

I have a QR code application that scans qr codes and it works. I want to add a redirection operation after the scanning has successfuly taken place.

Here is my code

import React, {Component} from "react";
import ReactDOM from 'react-dom';
import { Redirect } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";


class QR extends Component {


      constructor(props) {
        super(props);
        this.state = {
          data: "Not Found"
        };
      }

    render() {
        return (
   
          <>
          <BarcodeScannerComponent
            width={500}
            height={500}
            onUpdate={(err, result) => {
              if (result) {
                this.setState({data: result.text});
         
                return <Redirect to={this.state.data} />
                
              }
              else this.setState({data: "Not Found"});
            }}
            
          />
          <p>{this.state.data}</p>
        </>

        );
      }

}


ReactDOM.render(
    <QR />,
    document.getElementById('qr-id')
);

Although after successful scanning has taken place, no redirect occurs. Can somebody point out a good way of doing redirects in react?

  • Use the other way to redirect (`const history = useHistory();` and `history.push(url);`) or conditionally render it: `{this.state.data !== "Not Found" && }` instead of returning it in an event handler (which does absolutely nothing) –  Aug 03 '21 at 07:58
  • I conditionally rendered although not sure why I get an error "Invariant failed", ```{this.state.data !==Not Found ? ( ) : (

    {this.state.data}

    )} ```
    – Áron Pop Adorján Aug 03 '21 at 08:14
  • Duplicate: [How to use Redirect in the new react-router-dom of Reactjs](https://stackoverflow.com/questions/43230194/how-to-use-redirect-in-the-new-react-router-dom-of-reactjs) –  Aug 03 '21 at 08:59

1 Answers1

0

useHistory hook can redirect to route

import React, { useState, useEffect } from "react";
import ReactDOM from 'react-dom';
import { useHistory } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";
const QR = () => {
    const { data, setData } = useState('Not Found');
    const history = useHistory();
    useEffect(()=>{
        if(data==='Not Found') {
            return;
        }
        history.push(data);
    }, [data])
    return
    <>
        <BarcodeScannerComponent
            width={500}
            height={500}
            onUpdate={(err, result) => {
                if (result) {
                    setData(result.text);
                }
                else setData("Not Found");
            }}

        />
        <p>{data}</p>
    </>
}
gu mingfeng
  • 1,010
  • 8
  • 10