I am using React-router-dom-V6
for navigation with Class Based Component
in my WebApp and I want to navigate from one page to another page, how can I achieve this ? in functional component there is Hook named useNavigate()
, how to navigate in class component?
Asked
Active
Viewed 5,769 times
1

MarioG8
- 5,122
- 4
- 13
- 29

Rutvik Prajapati
- 188
- 1
- 3
- 11
3 Answers
1
You can use Navigate component for navigation in class components.
import * as React from "react";
import { Navigate } from "react-router-dom";
class LoginForm extends React.Component {
state = { user: null, error: null };
async handleSubmit(event) {
event.preventDefault();
try {
let user = await login(event.target);
this.setState({ user });
} catch (error) {
this.setState({ error });
}
}
render() {
let { user, error } = this.state;
return (
<div>
{error && <p>{error.message}</p>}
{user && (
<Navigate to="/dashboard" replace={true} />
)}
<form onSubmit={event => this.handleSubmit(event)}>
<input type="text" name="username" />
<input type="password" name="password" />
</form>
</div>
);
}
}

Dmitriif
- 2,020
- 9
- 20
-
thank you @Dmitriif but I wanted to navigate from on Press() is there any other method is there? here is scenario onPressEdit = (item) => { Navigate("/editemployee", { replace: true, state: { ...item } }); }; – Rutvik Prajapati Jan 03 '22 at 08:26
-
Hi @RutvikPrajapati for this you can use `withRouter` mechanism. [withRouter](https://v5.reactrouter.com/web/api/withRouter) Given you wrapped your class component with `withRouter` you can then call - `this.props.history.replace('/login');` to redirect.... Note that `.replace` has some alternatives too. – pjoshi Aug 16 '22 at 05:14
1
React Router v6 recommends React hooks. As we can read in official docs :
React Router v6 makes heavy use of React hooks, so you'll need to be on React 16.8 or greater before attempting the upgrade to React Router v6.

MarioG8
- 5,122
- 4
- 13
- 29
-
Ok i will, @MarioG8 but for this case do you have any suggestion? – Rutvik Prajapati Jan 03 '22 at 08:38
-
1No i have not ! I like to stick to the documentation, it limits many unpleasant surprises ;-) But it's your choice ...:-D Best regards and Good Luck ! – MarioG8 Jan 03 '22 at 08:41
1
I found a way, but please do not use in real apps instead use functional component with react-router-dom-v6,
import React, { Component } from "react";
import { connect } from "react-redux";
import { Navigate, useNavigate } from "react-router-dom";
import "./EmployeeList.css";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import { deleteEmployee } from "../redux/employee/employeeAction";
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
const StyledTableRow = styled(TableRow)(({ theme }) => ({
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover,
},
//hide last border
"&:last-child td, &:last-child th": {
border: 0,
},
}));
class EmployeeList extends Component {
constructor(props) {
super(props);
this.state ={
redirect : false,
data : {}
}
}
componentDidMount(){
this.setState({
redirect : false,
data : {}
})
}
deleteUser = (id) => {
this.props.deleteEmploy(id);
};
onPressEdit = (item) => {
// Navigate("/editemployee", { replace: true, state: { ...item } });
// return <Navigate to="/editemployee" replace={true} />
this.setState({
redirect: true,
data : {
...item
}
})
};
render() {
if(this.state.redirect) {
return <Navigate to="/editemployee" state={this.state.data}/>
}
return(
<div className="container">
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell align="center">Name</StyledTableCell>
<StyledTableCell align="center">Email</StyledTableCell>
<StyledTableCell align="center">Number</StyledTableCell>
<StyledTableCell align="center"></StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{this.props.employeeList.map((item) => {
return (
<StyledTableRow key={item.id}>
<StyledTableCell align="center">
{item.name}
</StyledTableCell>
<StyledTableCell align="center">
{item.email}
</StyledTableCell>
<StyledTableCell align="center">
{item.number}
</StyledTableCell>
<StyledTableCell align="center">
<Stack direction="row" spacing={2}>
<Button
variant="outlined"
onClick={() => this.deleteUser(item.id)}
>
Delete
</Button>
<Button
variant="contained"
onClick={() => this.onPressEdit(item)}
>
Edit
</Button>
</Stack>
</StyledTableCell>
</StyledTableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return { employeeList: state.employee.employee };
};
const mapDispatchAToProps = (dispatch) => ({
deleteEmploy: (id) => dispatch(deleteEmployee(id)),
});
export default connect(mapStateToProps, mapDispatchAToProps)(EmployeeList);

Rutvik Prajapati
- 188
- 1
- 3
- 11