Reputation: 85
I'm new to react and I would like to set a routing for my application. I work with react-router-dom and I have a connection component and a create component. I would like to redirect the user on create once he is logged in. Here is my code :
import React, { useState } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Aproove from "aproove/aproove";
import './App.css';
import Connection from './components/Connection';
import Create from './components/Create';
import Settings from './components/Settings';
const App = (props) => {
const [file, setFile] = useState(window.getFile);
const [aproove, setAproove] = useState(new Aproove());
//Get called when the user press "Connect" in connection component
const handleConnect = (email, password) => {
aproove.login(email, password).then(result => verifyConnection(result.data.result));
}
const verifyConnection = (result) => {
if(result!=="") {
console.log("validated");
//If conenction validated, redirect to create route
handleLocation("create");
}
else console.log("rejected");
}
const handleLocation = (path) => {
//Write here how to change route in function
}
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/connection">Connection</Link>
</li>
<li>
<Link to="/create">Create</Link>
</li>
<li>
<Link to="/settings">Settings</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/connection">
<Connection
onConnect={handleConnect}/>
</Route>
<Route path="/create">
<Create />
</Route>
<Route path="/settings">
<Settings />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
I already tried with history hook but without any success.
Thank you for any help ! :)
Upvotes: 0
Views: 2707
Reputation: 490
You can use the useHistory hook (https://reactrouter.com/web/api/Hooks) or the Redirect (https://reactrouter.com/web/api/Redirect).
Upvotes: 1