How to Redirect to Another Page in Reactjs When a If Condition Is Executed

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



Leave a reply



Submit