Create new routes react router
Here's an example of how to create new routes in React Router:
Step 1: Import React Router
In your React component, import React Router:
import { BrowserRouter, Route, Switch } from 'react-router-dom';
Step 2: Create a new route
Create a new route by wrapping your component with the Route
component:
<Route path="/new-route" component={NewRouteComponent} />
Replace NewRouteComponent
with the name of your new component.
Step 3: Define the route path
The path
prop specifies the URL path that the route should match. For example, /new-route
will match the URL /new-route
.
Step 4: Define the route component
The component
prop specifies the React component that should be rendered when the route is matched. In this example, NewRouteComponent
will be rendered when the URL /new-route
is matched.
Step 5: Add the new route to the router
Add the new route to the Switch
component, which is used to render the first matching route:
<BrowserRouter>
<Switch>
<Route path="/new-route" component={NewRouteComponent} />
<!-- other routes -->
</Switch>
</BrowserRouter>
Step 6: Create the new route component
Create a new React component for the new route:
function NewRouteComponent() {
return (
<div>
<h1>New Route Component</h1>
<!-- content for the new route -->
</div>
);
}
Step 7: Add the new route component to the App component
Add the new route component to your App component:
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/new-route" component={NewRouteComponent} />
<!-- other routes -->
</Switch>
</BrowserRouter>
);
}
That's it! You've created a new route in React Router.
Here's the complete code:
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
function NewRouteComponent() {
return (
<div>
<h1>New Route Component</h1>
<!-- content for the new route -->
</div>
);
}
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/new-route" component={NewRouteComponent} />
<!-- other routes -->
</Switch>
</BrowserRouter>
);
}
export default App;
Note: Make sure to replace NewRouteComponent
with the actual name of your new component.