I am converting an application over from jquery to react and I have a Kjua QR code component that I'm working on. My previous code creates the Kjua element in javascript
const qrcode = kjua({
text: target_url,
render: 'svg',
size: 200,
mode: 'image',
ecLevel: 'Q',
mSize: 25,
quiet: 2,
image: document.getElementById("logo"),
});
This references a 'logo' image in the DOM that references an SVG.
converting this over to react, I found the Kjua-react wrapper to use the library within react. Setting this up without the image overlay works fine:
function QRCode() {
const target_url = 'something';
return <Kjua text={target_url} render="svg" size="200" ecLevel="Q" mSize="25" quiet="2"/>;
}
ReactDOM.render(<QRCode />, document.getElementById("root"));
But I'm not sure how to reference the logo within react, and introducing the image overlay like the following:
function QRCode() {
const target_url = 'something';
return <Kjua text={target_url} render="svg" size="200" ecLevel="Q" mSize="25" quiet="2" mode="image" image="document.getElementById('logo')"/>;
}
ReactDOM.render(<QRCode />, document.getElementById("root"));
Gives the following error:
Uncaught TypeError: t.getAttribute is not a function
The above error occurred in the <Kjua> component
Uncaught TypeError: t.getAttribute is not a function
How do you render the image or create an HTMLImageElement and reference that within a react component?
Thanks.
CodePudding user response:
There are several ways:
The first. Pass image node through the props to target component
function QRCode({image}) {
const target_url = 'something';
return <Kjua text={target_url} render="svg" size="200" ecLevel="Q" mSize="25" quiet="2" mode="image" image={image}/>;
}
const image = document.getElementById('logo')
ReactDOM.render(<QRCode image={image}/>, document.getElementById("root"));
The second. Because sometimes it's not so trivial to pass a props you can just get reference to image node inside react component itself
function QRCode() {
const target_url = 'something';
const [image, setImage] = useState(null);
useEffect(() => {
setImage(document.getElementById('logo'))
}, [])
return image ? <Kjua text={target_url} render="svg" size="200" ecLevel="Q" mSize="25" quiet="2" mode="image" image={image}/> : null;
}
ReactDOM.render(<QRCode/>, document.getElementById("root"));
The third. If you are sure that when you render an element you have access to DOM you can replace useEffect on useMemo to get image synchronously
function QRCode() {
const target_url = 'something';
const image = useMemo(() => document.getElementById('logo'), [])
return <Kjua text={target_url} render="svg" size="200" ecLevel="Q" mSize="25" quiet="2" mode="image" image={image}/>;
}
ReactDOM.render(<QRCode/>, document.getElementById("root"));
P.s. The problem in your code that you pass to image prop string and kjua code behind react Kjua expect that image would be a DOM Element, so this is why you get exception.
