- Introduction
In this section, we’ll explore setting up React Router in your React application. Geek and Gal will guide you through the process in a fun, easy-to-understand way, suitable for beginners and advanced users alike!
So, we've learned about React Router, but how do we set it up in our app?
Yeah, I want to know how to get it running!
No worries! Let's go through the steps together!
- Step 1: Installing React Router
First, we need to install the
react-router-dom
package. Run this command in your project directory:
npm install react-router-dom
- Step 2: Importing Components
Now, let's import the necessary components from
react-router-dom
like
BrowserRouter
,
Route
, and
Link
!
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
- Step 3: Setting Up Routes
With the components imported, let's set up the routes using the
Router
,
Route
, and
Link
components.
That's it? It's like magic!
Yup! It's super easy! Here's an example:
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
);
}
Wow, I can see how it all comes together now! We wrap our app in a
Router
, use
Link
for navigation, and
Route
to render the correct components!
Exactly! Now you're ready to set up React Router in your app!
- Conclusion
Setting up React Router is a breeze! Just follow these steps: install the
react-router-dom
package, import the necessary components, and set up your routes using BrowserRouter
, Route
, and Link
. Now you can create dynamic and flexible routing in your React apps like a pro! 🚀