Why not use this npm package? npmjs.com/package/react-qr-code
Also you really dont want to have useEffects without a dependency array... It will execute the useEffect code on every render which is never what you want.
This is probably what you want:
useEffect(() => { setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrUrl}`) }, [qrUrl])
Although in your example I wouldnt use a useEffect hook at all, you can keep it all in the generateQR function:
const generateQR = useCallback(() => { let qrValue = inputRef.current.value.trim() if(!qrValue) return setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`) setQrCodeStatus("active") }, []);
Or even make it an actual form submit, so you dont have to use refs:
function App() { const [qrCode, setQrCode] = useState(""); const [status, setQrCodeStatus] = useState(""); const generateQR = useCallback((formEvent) => { formEvent.preventDefault() const qrValue = formEvent.target.elements['qr_code'].value.trim() if(!qrValue) return setQrCode(`http://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrValue}`) setQrCodeStatus("active") }, []); const inputChange = useCallback(event => { if(event.target.value === '') setQrCodeStatus('inActive'); }, []); return ( <div className={ `wrapper ${active} === 'active' ? "wrapper active" : "wrapper"` }> <header> <h1>QR Code Generator</h1> <p>Paste a url or enter text to create QR code</p> </header> <form class="form" onSubmit={generateQR}> <input onChange={inputChange} type="text" id="qr_code" name="qr_code" spellcheck="false" placeholder="Enter text or url" /> <button type="submit">Generate QR Code</button> </form> <div class="qr-code"> <img src={qrImg} alt="qr-code" /> </div> </div> ); }
Thanks Rense Bakker! Your feedback is really useful for my react learning...
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Why not use this npm package? npmjs.com/package/react-qr-code
Also you really dont want to have useEffects without a dependency array... It will execute the useEffect code on every render which is never what you want.
This is probably what you want:
Although in your example I wouldnt use a useEffect hook at all, you can keep it all in the generateQR function:
Or even make it an actual form submit, so you dont have to use refs:
Thanks Rense Bakker! Your feedback is really useful for my react learning...