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 ment the code for understand well
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 ment the code for understand well
Share Improve this question edited Dec 4, 2021 at 10:43 Marcel Kohls 1,89720 silver badges31 bronze badges asked Nov 29, 2021 at 15:31 Pernot BenjaminPernot Benjamin 531 gold badge3 silver badges6 bronze badges 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? – Giao 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. – lux Commented Nov 29, 2021 at 15:37
- @Giao 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 – Pernot Benjamin Commented Nov 29, 2021 at 15:40
- @lux oh, i dont know – Pernot Benjamin Commented Nov 29, 2021 at 15:40
-
Instead of the function
handleClick
you can use thereact-router
library and create the link with the<Link/>
ponent. In this way it works like a normal<a>
link. – Giao Commented Nov 29, 2021 at 15:53
2 Answers
Reset to default 4If 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.
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>
ponent) tag if you can, this is prefered way.