Reputation: 55
How to add target='_blank' in navigate?
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate(`/record`, {
state: {
eventId: event.id,
}
});
Upvotes: 2
Views: 9730
Reputation: 202856
The navigate
function isn't capable of doing this, it can only navigate within the app in the same window/tab.
You can use the following:
Link
passing a target="_blank"
prop.
<Link to="/record" target="_blank">
/record
</Link>
Anchor tag using a target="_blank"
attribute.
<a href="/record" target="_blank">
/record
</a>
window.open
in a callback.
const navigateOutApp = () => window.open("/record", "_blank", "noreferrer");
...
<button type="button" onClick={navigateOutApp}>
/record
</button>
If you need to also pass "state" then you will need to temporarily store it in localStorage and retrieve it when the app and target component mount.
const navigateExternal = (target, options) => {
if (options.state) {
localStorage.setItem("state", JSON.stringify(options.state));
}
window.open(target, "_blank", "noreferrer");
};
const Bar = () => {
const [state, setState] = useState(JSON.parse(localStorage.getItem("state")));
const location = useLocation();
useEffect(() => {
localStorage.removeItem("state");
}, []);
useEffect(() => {
if (location.state) {
setState(location.state);
}
}, [location]);
useEffect(() => {
console.log("Passed state", { state });
}, [state]);
return (
<>
<h1>Bar</h1>
<div>State: {JSON.stringify(state)}</div>
</>
);
};
Upvotes: 5
Reputation: 906
Hello You can use a simple approach for this
<Link to="/yourRoute" target="_blank">
Take me to other page
</Link>
According to react-router-dom
the <a>
tag is replaced by <Link>
tag so you can use all <a>
tag attributes on Link
tag.
Upvotes: 0