React open new tab
In React, you can open a new tab by using the target
attribute on the a
tag and setting it to _blank
. Here's an example:
<a rel="nofollow" target="_blank" href="https://www.example.com" target="_blank">Open in new tab</a>
This will open the link in a new tab when the user clicks on it.
If you want to open a new tab programmatically, you can use the window.open()
method:
import React, { useState } from 'react';
function MyComponent() {
const [url, setUrl] = useState('https://www.example.com');
const handleClick = () => {
window.open(url, '_blank');
};
return (
<div>
<a rel="nofollow" target="_blank" href="#" onClick={handleClick}>
Open in new tab
</a>
</div>
);
}
In this example, the handleClick
function is called when the user clicks on the link. It uses the window.open()
method to open the URL in a new tab.
You can also use the react-router-dom
library to open a new tab. For example:
import { Link } from 'react-router-dom';
function MyComponent() {
return (
<div>
<Link to="/example" target="_blank">
Open in new tab
</Link>
</div>
);
}
In this example, the Link
component is used to create a link to the /example
route. The target
attribute is set to _blank
to open the link in a new tab.
Note that the target
attribute is not supported in all browsers, so you may want to use a polyfill or a fallback solution if you need to support older browsers.