Home > database >  how to set the input text in react by taking it from from the url?
how to set the input text in react by taking it from from the url?

Time:02-14

I am trying to input a location as text input I want qr code to show the blow and location is the dynamic input we put in the input field https://google.com?location={location} ?

How can i set the url as above and put the location as input? showup in qr code

so input will be the location from the url which can be any location and the qr code should show <url/ currently i am using the below code but i can only get the input field showup in the qr code .

import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  
  return (
    <div className="App">
      <h3>Generate and download a QR code image in React Omneo</h3>
      <div className="qr-input">
        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />
      </div>
      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />
      
    </div>
  );
}

export default App;

CodePudding user response:

//add to the top
import { useEffect } from 'react'

//add above return
useEffect(() => {
    setInputText(window.location.href);
  })

CodePudding user response:

If the URL only has one parameter (location) you can split and get the rest. If there are more parameters you can split by '&' then location

useEffect(() => {
    setInputText(window.location.href.split("location=")[1]);
}, [])

  • Related