Routing
Effective navigation is crucial for creating dynamic single-page applications. "Startup" offers a routing system that allows you to manage navigation seamlessly.
Setting Up Routing
Installation: Ensure you have the required packages installed. If not, you can install them using npm or yarn.
bashCopy codenpm install react-router-dom
Basic Router: Create a basic router in your application to handle different routes.
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
export default App;
Navigation Links: Create navigation links using the Link
component from "react-router-dom."
// Navigation.js
import React from 'react';
import { Link } from 'react-router-dom';
function Navigation() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
export default Navigation;
Handling Route Parameters
You can also handle route parameters to create dynamic routes. For example:
// ProductDetail.js
import React from 'react';
import { useParams } from 'react-router-dom';
function ProductDetail() {
const { productId } = useParams();
return (
<div>
<h2>Product Detail</h2>
<p>Product ID: {productId}</p>
</div>
);
}
export default ProductDetail;
Redirects and 404 Pages
You can handle redirects and create a custom 404 page using the Redirect
and Switch
components:
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
import NotFound from './NotFound';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/products/:productId" component={ProductDetail} />
<Redirect from="/info" to="/about" />
<Route path="/404" component={NotFound} />
<Redirect to="/404" />
</Switch>
</Router>
);
}
export default App;
Conclusion
With the routing and navigation capabilities of "Startup" along with the "react-router-dom" library, you can create complex navigation structures, handle route parameters, and create redirects and custom 404 pages with ease, making your web application highly dynamic and user-friendly.