React Router - Open Link on new Tab and Redirect to Home Page
18,709
You don't need to create a new route for the thing you are trying to achieve. You could add an onClick
handler to the MenuItem
like this:
<NavDropdown eventKey={3} id="formId" title="Registration">
<LinkContainer to="/registration/financial-aid">
<MenuItem eventKey={3.1}>Financial Aid</MenuItem>
</LinkContainer>
<LinkContainer
to="/">
<MenuItem onClick={this.handlePoliciesClick} eventKey={3.2}>Policies</MenuItem>
</LinkContainer>
</NavDropdown>
And then in same component add the handler:
handlePoliciesClick = () => {
window.open(HandbookDoc, '_blank');
}
Remember to import your HandbookDoc
.
Related videos on Youtube
Author by
Jonca33
Updated on September 15, 2022Comments
-
Jonca33 over 1 year
Using React Router 4.2
My attempt is to open a new tab upon clicking on a navigation link and at the same time be redirected to the site homepage.
ie: Navigation bar: clicking on Policies
Even though the code bellow behaves as the requirements above: Is this the advisable way to go about it? Aiming to learn best practices here on Routes.js.
//Routes.js import HandbookDoc from './policies.pdf' ... <Route path="/registration/policies" component={() => window.open(`${HandbookDoc}`,'_blank').then(window.location= '/')} />
....
//Navigation.js (using react-router-bootstrap) <NavDropdown eventKey={3} id="formId" title="Registration"> <LinkContainer to="/registration/financial-aid"> <MenuItem eventKey={3.1}>Financial Aid</MenuItem> </LinkContainer> <LinkContainer to="/registration/policies"> <MenuItem eventKey={3.2}>Policies</MenuItem> </LinkContainer> </NavDropdown>
-
Jonca33 almost 6 yearsThank you so much, visualizing your explanation/suggestion through the code made sense in my head now. The only issue is that
browserHistory
is not redirecting home... -
Jackyef almost 6 yearsHave you removed the
to
attribute in yourLinkContainer
? -
Jonca33 almost 6 yearsI did. In fact, I removed LinkContainer all together, cause
to
is required on their api, it was throwing an error otherwise. -
Jackyef almost 6 yearsWeird. Is browserHistory redirecting you somewhere else? Or it just doesn't work at all?
-
Jonca33 almost 6 yearsit stays on the same page. Scenario 2. If I leave
to="/"
it redirects me home. Which means BrowserHistory alone is not getting triggered. But the open on new tab click handler works.