Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
Pernot Benjamin Avatar asked Dec 10 '25 04:12

Pernot Benjamin


2 Answers

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.

like image 58
Judith Hartmann Avatar answered Dec 11 '25 21:12

Judith Hartmann


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 || event.button === 1) {
    window.open(`/document/${documentID}`, "_blank")
  } else if (event.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.

like image 25
Petr Kratochvíla Avatar answered Dec 11 '25 22:12

Petr Kratochvíla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!