Redirection based on Url works with React Router library (run npm install react-router-dom
to install). This should work:
App.ts
function App() {
// Wrap your HomePage inside a router to access history context
return (
<Router>
<Route path="/" component={HomePage}/>
</Router>
);
}
HomePage.tsx
import {withRouter} from 'react-router-dom';
function HomePage(props) {
const goTo: Function = (url: string) => {
props.history.push(url);
};
return (
<div>
<Card className={classes.root} onClick={() => goTo("/userInfo")}>
<CardActionArea>
<CardContent>
UserInfo
</CardContent>
</CardActionArea>
</Card>
<Router>
<Route
path="/userInfo"
render={props => <Hook {...props} foo="bar"/>}
/>
</Router>
</div>
);
}
// instead of export default HomePage;
export default withRouter(HomePage);
Some explaination :
Router component will basically iterate through every child Route. Each time the current URL matches a path prop, it will render the given component. Some route context will automatically be passed to child components afterwards. This allow the given child component to change URL and re-render the Routes, if needed.
HomePage is wrapped in Router, so it can manipulate URL and update render. Since you didn't specified any history context, all the Routers will use the same default one. Now let's say your user is located on the root URL "/". HomePage is rendered and visible, and so is the Card component, but Hook is not.
The onClick method will trigger the goTo local function, which will basically push a new entry into your browser history (this update the URL and refresh the render). Now both "/" and "/userInfo" match current URL (a match occurs when the current URL starts with the one given by the path).
If you want to pass hidden props, and this props are accessible by the parent component, then use render
prop instead of component
. This allows you to pass a functional component to Route, to which you can freely add and/or remove props.
So in this example, I just added the foo
prop to Hook, but you can do pretty much whatever you want here.
EDIT
If you don't want your HomePage and your Hook to render simultaneously, then either set HomePage path to something different (like "/home") or add the exact prop like so :
App.ts
function App() {
// Wrap your HomePage inside a router to access history context
return (
<Router>
<Route path="/" exact component={HomePage}/>
</Router>
);
}
This will force an exact match, aka it won't render if the URL is not exactly "/"