I\'m trying to make a button that only redirects the user to a new page after validation is completed correctly.
Is there a way of doing something like this? How to I g
Like Purgatory said you can do it without using <Redirect />
, but otherwise you could make your component a stateful component and then do a conditional render like so
render() {
!this.state.redirect ?
<button onClick={this.saveAndContinue}>Save and Continue</button> :
<Redirect to='/other_tab'>
}
And let the saveAndContinue()
change the component state.
saveAndContinue () {
var valid = validator.validate(this.props.form)
if (valid) {
axios.post('/path')
this.setState({redirect: true});
} else {
validator.showErrors()
}
}
When the state changes it would cause a re-render and this time the <Redirect />
would be rendered.
Note: I didn't actually run this code snippet, so it may contain (hopefully minor) errors.
I needed to do this today. Here's my code, mind i decided to make this a HOC that you can choose to wrap or not wrap. For use cases that have multiple redirect cases you'll definitely want to use this inline instead of as a wrapper.
import React from 'react';
import {Redirect} from 'react-router';
interface IConditionalRedirectProps {
shouldRedirect: boolean,
to: string
}
export const ConditionalRedirect: React.FC<IConditionalRedirectProps> = (props) => {
const {shouldRedirect, to, children} = props;
if (shouldRedirect) {
console.log('redirecting');
return <Redirect to={to}/>
} else {
return (
<>
{children}
</>
)
}
};
Usage:
<ConditionalRedirect shouldRedirect={isButtonClicked()}
to={'some url'}>
<Normal Elements here>
</ConditionalRedirect>
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