Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Open <a> tag using JavaScript

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>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!