How to Redirect to another page in ReactJS when a IF condition is executed?
// Are You using BrowserRouter means you can use like this
import PropTypes from 'prop-types';
var users={
name:'bddebashis',
password:'debashis111249'
}
class Home extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
static contextTypes = {
router: PropTypes.object,
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
if(data.get('usr')==users.name && data.get('paswd')==users.password){
this.context.router.history.push("/Dashboard")
}
}
}
How to redirect to some page if condition is true using react?
You can use Redirect from react-router-dom.
import { Route, Redirect } from 'react-router-dom';
const PrivateRoute = () => {
const isAdmin = getUser();
return (
<Route render={isAdmin ? (
<Redirect to='/confirm' />
) : (
<NotFound />
)
} />
)
}
You can similarly use a Router Switch statement. Implementation can be found in the react router doc: https://reactrouter.com/web/api/Switch
Alternatively, you may use history.push('/404'). You can find more info under this question: How to push to History in React Router v4?
Conditional Redirect Using React Router
To manually redirect to a different route you need to use history.push(url)
from the props that react-router-dom
injects to the component.
If props.history
is undefined you will need to wrap the component with withRouter
HOC or use useHistory
(hooks are available from V5.1) hook from react-router-dom
const addFavorite = (card) => {
if(!props.loggedUser.id) {
props.history.push('/login')
return
}
// add to favorites
}
<Button onClick={() => addFavorite(card)} />
React Router Redirect Conditional
As discussed you should have access to the history
object via this.props.history
as described here.
If you look into the push
function this will redirect you to any route you need.
For example:
// Use push, replace, and go to navigate around.
this.props.history.push('/home', { some: 'state' })
https://reacttraining.com/react-router/web/api/history
How to use Redirect in version 5 of react-router-dom of Reactjs
You have to use setState
to set a property that will render the <Redirect>
inside your render()
method.
E.g.
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
axios.post(/**/)
.then(() => this.setState({ redirect: true }));
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/somewhere'/>;
}
return <RenderYourForm/>;
}
You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow
That said, I would suggest you to put the API call inside a service or something. Then you could just use the history
object to route programatically. This is how the integration with redux works.
But I guess you have your reasons to do it this way.
Related Topics
Reactjs: Expected Onclick Listener to Be a Function, Instead Got Type String
How to Count the Entire Number of Rows in a Datatable
Download Image as File in Typescript
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
Node.Js MySQL Query in a for Loop
Trying to Add Image to Pdf Using Jspdf
Filtering Item from Nested Object Array in Typescript
How to Set Page Size and Set Margin in Print in Internet Explorer With JavaScript and CSS
Webcam Js Error in Chrome: Could Not Access Webcam
Disable Click Outside of Bootstrap Modal Area to Close Modal
How to Show a Confirm Message Before Delete
React Router Dom Returns a Blank Page When Going to a Particular Route
Blob Download Is Not Working in Ie
How to Combine First Name and Last Name in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
Ios Safari/Chrome - Unwanted Scrolling When Focusing an Input Inside the Modal