We have a web application where we load the pdf link from BE and open it using JavaScript like this.
const openLink = () => {
window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
}
This works fine for the web. But we use this same web app in a mobile application as well. We have a native android and IOS app which provides a web browser and runs the same web app. Users won't feel any difference it will work like a normal mobile app.
But for that mobile app doesn't work above code. A normal <a> tag works fine in the mobile app environment as well.
<a href='http://www.africau.edu/images/default/sample.pdf' target="_blank">Link</a>
Now our goal is to render a normal tag and mimic the native onClick event using JavaScript. For some security reason, we cannot directly render the <a> tag with the href instead we set href later using refs. But now we need a way to open the link instead of window.open()
This use case may look strange but we have to follow this for some more concerns. This is my current code
function App() {
const tag = useRef();
const openLink = () => {
// window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
tag.current.href = 'http://www.africau.edu/images/default/sample.pdf' // set the loaded dynamic pdf link from BE
// open the link code ...
}
return (
<div className="App">
<button onClick={openLink}>click me</button>
<a href='' ref={tag} target="_blank" style={{display:"none"}}></a>
</div>
);
}
In order to work you must be encapsulating the button inside <a> tag
Using style={{display: 'none'}} won't allow you to use the <a> tag
const tag = useRef();
const openLink = () => {
// window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
tag.current.href = "http://www.africau.edu/images/default/sample.pdf"; // set the loaded dynamic pdf link from BE
// open the link code ...
};
return (
<div className="App">
<a href="" ref={tag} target="_blank">
<button onClick={openLink}>click me</button>
</a>
</div>
);
Demo: Demo codesandbox