Reputation: 2265
I'm trying to use useHistory from react-router-dom when I click a button, but it returns undefined, so I can't push the new page url.
My component is an inner component of a Route as you can see in the following picture:
This is my simple Login component code:
export default function Login() {
let history = useHistory();
function onEnterAsGuest() {
history.push("/example");
}
return (
<Container>
<Logo></Logo>
<WelcomeTextContainer>
<StyledHeading>Welcome!</StyledHeading>
</WelcomeTextContainer>
<ButtonContainer>
<Button
primary
text={"Enter as guest"}
onClick={onEnterAsGuest}
block
/>
</ButtonContainer>
</Container>
);
}
This is how I instantiate the Router:
import { HashRouter as Router, Switch, Route, Link } from "react-router-dom";
...
export default function App() {
const { width } = useWindowDimensions();
return (
<Router>
<Switch>
{Routes(width)}
<Route path="*">
<p>
Wrong path! Return to <Link to="/">Home Page</Link>
</p>
</Route>
</Switch>
</Router>
);
}
This is how I define my Routes:
export default function Routes(width: number) {
return routes.map((route) => {
return (
<Route exact path={route.path} key={route.path}>
{width > 720
? DesktopVersion(route.component)
: MobileVersion(route.component)}
</Route>
);
});
}
And this is the routes
object I loop through:
const routes: IRoute[] = [
{
path: "/",
component: Login,
},
{
path: "/example",
component: () => (
<p style={{ marginTop: "100px" }}>
<Link to="/another" style={{ color: "salmon" }}>
This is a link
</Link>
</p>
),
},
{
path: "/another",
component: () => (
<p>
<Link to="/example" style={{ color: "salmon" }}>
Hello world
</Link>
</p>
),
},
];
Could you please help me to debug this? Don't know where else to check for errors...
Thanks in advance.
Upvotes: 1
Views: 524
Reputation: 19813
Don't call the component as a function.
Use <Routes width={width}/>
instead of {Routes(width)}
.
Upvotes: 1