I need some help to solve the following issue with using React.
In some web app I have a landing page, where I want to redirect the user to the login page in case she or he is not logged in.
I want to use the following landing page (taken from some tutorial I found on the net) in order to use it as a model for mine.
The problem is that this is a function component while my landing page is a class component. According to what I understand I guess I need to consider the code inside useEffect and (somewhat) transfer it to componentDidMount() in my class component. But I don't know how to do that. history.replace will not work in a class component (no Hooks in Classes). Any advice from a more React experienced user will be very welcome.
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useHistory } from "react-router";
import "./Dashboard.css";
import { auth, db, logout } from "./firebase";
....
function Dashboard() {
const [user, loading, error] = useAuthState(auth);
const [name, setName] = useState("");
const history = useHistory();
....
useEffect(() => { // Important part for my question !
if (loading) return;
if (!user) return history.replace("/");
....
}, [user, loading]);
return (
<div>
{/*...*/}
<button className="dashboard__btn" onClick={logout}>
Logout
</button>
</div>
);
}
export default Dashboard;
Here is what I tried on my Class Component:
class MyCompo extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("--componentDidMount(MyCompo)--");
const { history } = this.props
history.push("/login");
}
.....
}
But I get the following error:
TypeError: history is undefined
componentDidMount
CodePudding user response:
Following the example on the React Router docs you can use withRouter if your component isn't already receiving the route props, otherwise you can access history from the props.
class MyComponent extends React.Component {
...
componentDidMount() {
const { history } = this.props
// do whatever with history here
}
...
}
CodePudding user response:
In react-router-dom version 5 there are a couple ways a class component can access the history object.
Rendered directly by a
Routecomponent via thecomponent, orrenderorchildrenfunction props so route props (i.e.history,location, andmatch) are passed.component:<Route path="....." component={MyCompo} />render:<Route path="....." render={routeProps => <MyCompo {...routeProps} />} />
Access the
historyobject from the passed route props:class MyCompo extends React.Component { componentDidMount() { const { history } = this.props; history.push("/login"); } ... }Decorated by the
withRouterHigher Order Component so the route props are injected.import { withRouter } from 'react-router-dom'; class MyCompo extends React.Component { componentDidMount() { const { history } = this.props; history.push("/login"); } ... } export default withRouter(MyCompo);
