I want to create a Notebook
application where I have a list of notebooks such as "Mathematics" and "Science". When I select one of the notebooks, I want to display a list of notes within that selected notebook. Then, when I click on a specific note, I want to open that note and display its content in a separate component, where I can either continue taking notes or edit the existing note.
I have created separate NotebookList
, Notebook
, and Note
components for this project.
I’m currently using React Router and I’m having trouble configuring the component and route structure to achieve this functionality.
Here’s what I have so far:
NotebookList.js
import { Link } from 'react-router-dom';
const NotebookList = () => {
return (
<div>
<h1>Notebooks</h1>
<ul>
<li><Link to="/notebook/mathematics">Mathematics</Link></li>
<li><Link to="/notebook/science">Science</Link></li>
{/* Add more notebook options here */}
</ul>
</div>
);
};
export default NotebookList;
Notebook.js
import { useParams } from 'react-router-dom';
const Notebook = () => {
const { notebookId } = useParams();
// Fetch the notes for the selected notebook using notebookId
return (
<div>
<h1>Notebook: {notebookId}</h1>
{/* Display the list of notes */}
</div>
);
};
export default Notebook;
Note.js
import { useParams } from 'react-router-dom';
const Note = () => {
const { notebookId, noteId } = useParams();
// Fetch the content of the selected note using notebookId and noteId
return (
<div>
<h1>Note: {noteId}</h1>
{/* Display the content of the note */}
</div>
);
};
export default Note;
App.js
import { BrowserRouter as Router, Route } from 'react-router-dom';
import NotebookList from './NotebookList';
import Notebook from './Notebook';
import Note from './Note';
const App = () => {
return (
<Router>
<Route exact path="/" component={NotebookList} />
<Route path="/notebook/:notebookId" component={Notebook} />
<Route path="/notebook/:notebookId/note/:noteId" component={Note} />
</Router>
);
};
export default App;
I would appreciate any guidance on how to properly configure the component and route structure to achieve the desired functionality.
2
Answers
The
Router
component inclusively renders all matches to the current URL path. If you want the components to render separately on their own then render the routes into theSwitch
component. Keep in mind that within theSwitch
that path order and specificity matters. Order the routed in the inverse order of path specificity, e.g. more specific paths before less specific paths. This eliminates the need to use theexact
prop in almost 100% of the use cases.Example: