how to route to another component in react code example
Example 1: how to redirect react router from the app components
state = { redirect: null };
render() {
if (this.state.redirect) {
return <Redirect to={this.state.redirect} />
}
return(
)
}
this.setState({ redirect: "/someRoute" });
Example 2: how to work react router another component
import React, { Fragment } from "react";
import "./index.css"
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
export default function App() {
const name = 'John Doe'
const isAuthenticated = false
return (
<Router>
<main>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to={`/about/${name}`}>About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Switch>
<Route path="/" exact component={Home} />
{
isAuthenticated ?
<>
<Route path="/about/:name" component={About} />
<Route path="/contact" component={Contact} />
</> : <Redirect to="/" />
}
</Switch>
</main>
</Router>
);
}
Example 3: how to redirect react router from the app components
state = { redirect: null };
render() {
if (this.state.redirect) {
return <Redirect to={this.state.redirect} />
}
return(
)
}