Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('App'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js
import './App.css'
import Release from './components/Release'
import {
BrowserRouter as Router,
Routes,
Route,
NavLink,
Link
} from "react-router-dom";
function App() {
return (
<div className="App">
<header className="App-header">
<Router>
<div>
<Link to="/release">Release Notes</Link>
</div>
<Routes>
<Route exact path="/release" element={<Release />}></Route>
</Routes>
</Router>
</header>
</div>
);
}
export default App;
Release.js
import React from "react"
const Release = () => {
return(
<div>
Release Notes - Goes here
</div>
)
}
export default Release
When I click the link "Release Notes" in app page, it is taking to Release page, however the link "Release Notes" is also showing as it is in App page.
This is what I am expecting > App page is having a link(Release), on click it should take to release page and display "Release notes -goes here" and should not show any other links again as it is in app page. But the release page is showing the link again "Release Notes" along with "Release Notes – Goes Here"
What I am doing wrong? I am just learning React js.
3
Answers
That release notes link will appear on every route because it is outside the Routes component. You need a default route:
It will be much simpler for you to understand how your application routes should look like and behave if you choose instead of composing the Route components nested one inside the other, to create a mapping of all the routes together with the hierarchy you fancy. Read the docs in this link: adding-a-router
routes.js file
main.js file
App.js file
In this example you can see that the router provider is wrapping the entire application and is initiated with a declaration of hierarchy. It is much cleaner and simpler to grasp.
You can learn from this example that the App has nothing inside except for the Outlet component that renders the different components by the specific route in the url. You can see that the LandingPage component is a sibling of the HomePage component and it has a default priority as the entry point to the application.
You can also see that the HomePage has 2 nested children routes inside of it. The beauty with this approach is that it all looks very clean, even the paths themselves. You do not need to write for example "/home/contact/…" but only the path itself.
The code is unconditionally rendering the
Link
, irrespective of any routes.Render a
Route
on the home"/"
path that simply renders theLink
to the"/release"
route.