My react router push isn’t redirecting to Home
component, while I’m passing with props the Home
path. It seems that the code is correct though.
import React, { Component } from "react";
const ErrorLogin = () => {
let back = () => {
this.props.history.push("/");
};
return (
<div className="wrapper">
<h1>Error</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
</p>
<button onClick={() => back()}>Back</button>
</div>
);
};
export default ErrorLogin;
3
Answers
Are the props passed down the component? and also don’t you need to have props in component parameters arguments?
You can use
useHistory
hook if you want to use function components.You’re mixing up React class components and function components. Your example is trying to get the props as you would from a class component, in a function component. To use React router in function components, you need to use the hooks API – in this case,
useHistory
.For completeness’ sake, here’s the equivalent using the class syntax. Note the
withRouter
HOC.Please note that you should probably be using function components going forwards. React router v6 doesn’t support class components and the larger React ecosystem is moving away from them.