user1250264
user1250264

Reputation: 905

react js Redirect to another url in the application

I am using react js and new at learning some of the calls. I have having some issue getting onclick function to redirect to another url in the application.

I have the following code

import { Redirect } from 'react-router-dom'

in the function

redirect() {

return <Redirect to="myComponent/subComponent"/>

}

I placed a break point and nothing happens

I also tried the following

redirect() {
  const myUrl='/myComponent/subComponnent'
  this.props.history.push(`${myUrl}`)
}

but the history is null

any help is greatly appreciated. thanks

Upvotes: 0

Views: 933

Answers (2)

abnaceur
abnaceur

Reputation: 262

If you need to redirect from inside a component/function you can use the history function as follow


const createHistory = require("history").createBrowserHistory;

Redirectpath = () => {
    let history = createHistory();
    history.push("/login");
    let pathUrl = window.location.href;
    window.location.href = pathUrl;   
}

Otherwise if you are creating a middleware for protect your routes and want to redirect to login page on error or an unauthorized access then you can :

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Redirect,
  Route,
} from "react-router-dom";
import Login from "./components/pages/Login";
import Home from "./components/pages/Home";

function App() {
  const checkAuth = () => {
    try {
      // To be replaced with you condition
      if (false) {
        return false;
      }

    } catch (e) {
      return false;
    }

    return true;
  }

  const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (
        <Component {...props} />
      ) : (
          <Redirect to={{ pathname: '/login' }} />
        )
    )} />
  )

  return (
    <div className="row">
      <Router>
        <Switch>
          <AuthRoute exact path="/" component={Home} />
          <Route exact path="/login" component={Login} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

Upvotes: 1

PrakashT
PrakashT

Reputation: 901

use BrowserRouter in your index.js file.

For an example

import {BrowserRouter} from 'react-router-dom'
 ReactDOM.render(
    <BrowserRouter basename={baseUrl}>
      <ChildComponent />
    </BrowserRouter>,
    document.querySelector('#root')
  );

Now history props works well.

Upvotes: 0

Related Questions