Bellow is a class component I'm using as the basis for a web page. As you can see, inside componentDidMount() I have two guard clauses that check if the GET contains a zaalId parameter, and this checks an endpoint to see if the corresponding object with that ID exists. If it does not exist, I would like it to immediately redirect to a different page. How can I do this? useNavigate only works in function components.
import React, { Component } from "react";
import { useNavigate } from 'react-router-dom';
import { withRouter } from 'react-router-dom';
class ReserveerForm extends Component
{
constructor(props) {
super(props);
this.state = {
startDate: new Date(),
endDate: new Date(),
roomId: null,
redirect: false
};
}
async componentDidMount() {
const zaalId = this.getZaalId();
const res = await fetch(`https://localhost:7260/Zaal/${zaalId}`);
const data = await res.json();
if (zaalId == null) {
console.log("ZaalId required");
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
return;
}
}
getZaalId = (event) => {
const queryParameters = new URLSearchParams(window.location.search);
const zaalId = queryParameters.get("zaalId");
return zaalId;
};
async validateZaal(zaalId) {
const res = await fetch(`https://localhost:7260/Zaal/${zaalId}`);
const data = await res.json();
if (zaalId == null) {
console.log("ZaalId required");
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
}
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = event => {
const zaalId = this.getZaalId();
event.preventDefault();
console.log(
`Renting room with id ${zaalId}
from ${this.state.startDate}
to ${this.state.endDate}`
);
};
getZaalId = event => {
const queryParameters = new URLSearchParams(window.location.search)
const zaalId = queryParameters.get("zaalId")
return (zaalId);
}
render() {
return (
< form onSubmit ={ this.handleSubmit}>
< label htmlFor = "startDate" > Start Date:</ label >
< input
type = "datetime-local"
name = "startDate"
value ={ this.state.startDate}
onChange ={ this.handleChange}
/>
< br />
< label htmlFor = "endDate" > End Date:</ label >
< input
type = "datetime-local"
name = "endDate"
value ={ this.state.endDate}
onChange ={ this.handleChange}
/>
< br />
< button type = "submit" > Rent Room </ button >
</ form >
);
}
}
export default ReserveerForm;
I've tried using this.props.navigation.navigate(); but this tells me "this.props.navigation is undefined" in the console.
CodePudding user response:
To redirect to a different page after a failed guard clause in a class component, you can use the history object provided by the withRouter HOC. First, make sure to wrap your component with withRouter:
import { withRouter } from 'react-router-dom';
class ReserveerForm extends Component {...}
export default withRouter(ReserveerForm);
Then, you can use the history.push method to redirect to a different page:
if (zaalId == null) {
console.log("ZaalId required");
this.props.history.push('/error');
return;
}
if (data.length === 0) {
console.log(`No zaal with ID ${zaalId} found`);
this.props.history.push('/error');
return;
}
This will redirect to the /error page if either of the guard clauses fail. Make sure to import withRouter at the top of your file.
CodePudding user response:
You can use the Navigate element in the render()
method:
render() {
if(this.state.redirect) {
return <Navigate to="/error" />
}
// normal code
}
Set the redirect
state variable to true in componentDidMount
to trigger the redirect.