Singh
Singh

Reputation: 207

How to navigate with history.push in React

Can I add my component name in: eg : this.props.history.push(<Sample/>)

I have an idea about adding the path in this: this.props.history.push("/Sample").

Or how can I navigate it to my component:

.catch((error) => {
    console.log("error", error);
    this.setState({
        finishedStep: false,
    });
    this.props.history.push("<Sample/>");
});

If the finished step is false, I want to navigate it to my <Sample> component.

Upvotes: 0

Views: 6120

Answers (1)

nitte93
nitte93

Reputation: 1840

Assuming you've already configured the corresponding route for the <Sample /> Component.

Wrap your component with react-router-dom

Install - react-router-dom

npm install --save react-router-dom

Example:

import { withRouter } from 'react-router-dom';

class YourComponent extends React.Component {
   handleSubmit = (user) => {
     saveUser(user).then(() =>
     this.props.history.push('/dashboard')
     )).catch((error) => {
      console.log("error", error);
      this.setState({
        finishedStep: false,
      });
      this.props.history.push("/Sample");
     })
   }      
   render() {
    return (
      <div>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }
}

export default withRouter(YourComponent)

Another approach that you could take without using react-router-dom is.

render() {
    if (this.state.finishedStep === false) {
      return <Redirect to='/Sample' />
    }

    return (
      <div>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }

Upvotes: 1

Related Questions