How to add target='_blank' in navigate?
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate(`/record`, {
state: {
eventId: event.id,
}
});
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>
</>
);
};