How to add target='_blank' in navigate?
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate(`/record`, {
state: {
eventId: event.id,
}
});
CodePudding user response:
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:
Linkpassing atarget="_blank"prop.<Link to="/record" target="_blank"> /record </Link>Anchor tag using a
target="_blank"attribute.<a href="/record" target="_blank"> /record </a>window.openin 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> </> ); };
Demo
CodePudding user response:
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.
