• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

102
Views
Open link in new tab when ctrl + click it in ReactJS?

I have a problem with that, I don't found the solution. How I can ctrl + click on a link for open in new tab ?

 function handleClick(documentID) {
    // if ctrl + click
    window.open(`/document/${documentID}`, "_blank")
    // else
    // navigate("/document/" + documentID)
  }

 <ListItem onClick={() => handleClick(document.id)}>

i have comment the code for understand well

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you have a link, please use an actual a element with a href. This is better for accessibility and you get the CTRL + click feature for free.

almost 3 years ago · Juan Pablo Isaza Report

0

You need to pass event to function instead just ID. This way you can check for Ctrl:

function handleClick(event) {
  const documentID = event.id;

  if (event.ctrlKey) {
    window.open(`/document/${documentID}`, "_blank")
  } else {
    navigate("/document/" + documentID)
  }
}

<ListItem onClick={(event) => handleClick(event)}>

You can also extend your function for mouse wheel click:

function handleClick(event) {
  event.preventDefault();

  const documentID = event.id;

  if (event.ctrlKey || e.button === 1) {
    window.open(`/document/${documentID}`, "_blank")
  } else if (e.type === 'click') {
    navigate("/document/" + documentID)
  }
}

<ListItem onClick={(event) => handleClick(event)} onMouseDown={(event) => handleClick(event)}>

Use anchor <a> (or react <Link> component) tag if you can, this is prefered way.

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error