Home > database >  How do i redirect to a page from button click in react from a component?
How do i redirect to a page from button click in react from a component?

Time:03-07

this is my app.js

<div
  className="flex-one main-content-box"
  style={{ height: "calc(100% - 55px)" }}
>
  <div className="arrow-navigation" style={{ top: topPosition }}></div>
  <Switch>
    <Route path="/" exact render={() => <DashBoard store={main} />} />
    <Route path="/newprocess" render={() => <div>DEFG</div>} />
    <Route path="/release" render={() => <div>ABCD</div>} />
  </Switch>
</div>

this is my process.jsx

<div className="saveblue mg-r-10" onClick={this.handleNewProcess} style={{cursor: "default"}}><i className="fas fa-plus pd-r-5" />New Process</div>

this the function

 handleNewProcess = () => {
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page 
    }

CodePudding user response:

You can use useNavigate().

    import { useNavigate} from "react-router-dom";

    const MyCompo= () => {
    
      let navigate = useNavigate();
      handleNewProcess = () => {
         navigate(`/newprocess/`);
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page 
    }

And as nos nart mentioned, this solution is fit only from react-router v6.

CodePudding user response:

You can also solve this issue using useHistory hook

    import { useHistory} from "react-router-dom";

    const MyCompo= () => {
    
      let history = useHistory();
      handleNewProcess = () => {
         history.push('/newprocess/');
        //HOW DO I REDIRECT THE CLICK FROM HERE TO "/newprocess" page 
    }

checkout this page , it has mentioned all the methods of redirection in react: Link

  • Related