2

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

5
  • I don't understand your problem. You want to open every time the link in a new tab or only when the user use ctrl+click? Commented Nov 29, 2021 at 15:33
  • Isn't ctrl+click to new window baked into browsers? FE code typically does not have to handle that explicitly. Commented Nov 29, 2021 at 15:37
  • @Giacomo i want to when i just click on my document, he's open on the same page where the link is and when i press ctrl + click on the link i want to open him in a new tab Commented Nov 29, 2021 at 15:40
  • @lux oh, i dont know Commented Nov 29, 2021 at 15:40
  • Instead of the function handleClick you can use the react-router library and create the link with the <Link/> component. In this way it works like a normal <a> link. Commented Nov 29, 2021 at 15:53

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Mouse wheel might not work, onAuxClick should be used instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.