Skip to content

Commit 9732532

Browse files
committed
Chang the route as a child route of main
1 parent e5b216e commit 9732532

File tree

2 files changed

+42
-12
lines changed

2 files changed

+42
-12
lines changed

src/main.jsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
import React from 'react';
22
import ReactDOM from 'react-dom/client';
33
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
4-
import Root from './routes/root';
4+
// import Root from './routes/root';
55
import ErrorPage from './error-page';
66
import Contact from './routes/contact';
7+
import Root, {loader as rootLoader} from './routes/root'
78
// import App from './App.jsx'
89
import './index.css';
910

11+
1012
const router = createBrowserRouter([
11-
{ path: '/', element: <Root />, errorElement: <ErrorPage /> },
12-
{ path: 'contacts/:contactId', element: <Contact /> },
13+
{
14+
path: '/',
15+
element: <Root />,
16+
errorElement: <ErrorPage />,
17+
loader: rootLoader,
18+
children: [{ path: 'contacts/:contactId', element: <Contact /> }],
19+
},
1320
]);
1421

1522
ReactDOM.createRoot(document.getElementById('root')).render(

src/routes/root.jsx

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1+
import { Outlet, Link, useLoaderData } from "react-router-dom";
2+
import { getContacts } from "../contacts";
3+
4+
export async function loader() {
5+
const contacts = await getContacts();
6+
return { contacts };
7+
}
8+
19
export default function Root() {
10+
const {contacts} = useLoaderData()
211
return (
312
<>
413
<div id="sidebar">
@@ -26,18 +35,32 @@ export default function Root() {
2635
<button type="submit">New</button>
2736
</form>
2837
</div>
29-
<nav>
38+
{contacts.length ? (
3039
<ul>
31-
<li>
32-
<a href={`/contacts/1`}>Your Name</a>
33-
</li>
34-
<li>
35-
<a href={`/contacts/2`}>Your Friend</a>
36-
</li>
40+
{contacts.map((contact) => (
41+
<li key={contact.id}>
42+
<Link to={`contacts/${contact.id}`}>
43+
{contact.first || contact.last ? (
44+
<>
45+
{contact.first} {contact.last}
46+
</>
47+
) : (
48+
<i>No Name</i>
49+
)}{" "}
50+
{contact.favorite && <span></span>}
51+
</Link>
52+
</li>
53+
))}
3754
</ul>
38-
</nav>
55+
) : (
56+
<p>
57+
<i>No contacts</i>
58+
</p>
59+
)}
60+
</div>
61+
<div id="detail">
62+
<Outlet />
3963
</div>
40-
<div id="detail"></div>
4164
</>
4265
);
4366
}

0 commit comments

Comments
 (0)