To create a simple Next.js page with a list on the left and detail display on the right, you can follow these steps. We'll set up a basic React component that leverages Next.js features like dynamic routing (optional) or React state to manage the list and detail view.
Here's a basic example using React state to keep things simple:
-
Create a new Next.js project if you haven't already:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
-
Create the component to display the list and details. You can create a new file under the pages directory. Let's call it index.js for simplicity.
// pages/index.js
import { useState } from 'react';
const IndexPage = () => {
// Sample data
const items = [
{ id: 1, name: 'Item 1', detail: 'This is the detail of item 1' },
{ id: 2, name: 'Item 2', detail: 'This is the detail of item 2' },
{ id: 3, name: 'Item 3', detail: 'This is the detail of item 3' },
];
const [selectedItem, setSelectedItem] = useState(null);
return (
<div style={{ display: 'flex' }}>
{/* Left side list */}
<div style={{ width: '30%', borderRight: '1px solid #ccc' }}>
<ul>
{items.map((item) => (
<li
key={item.id}
onClick={() => setSelectedItem(item)}
style={{
cursor: 'pointer',
padding: '10px',
backgroundColor: selectedItem?.id === item.id ? '#f0f0f0' : '#fff',
}}
>
{item.name}
</li>
))}
</ul>
</div>
{/* Right side details */}
<div style={{ flex: 1, padding: '10px' }}>
{selectedItem ? (
<div>
<h2>{selectedItem.name}</h2>
<p>{selectedItem.detail}</p>
</div>
) : (
<p>Please select an item to see the details.</p>
)}
</div>
</div>
);
};
export default IndexPage;
Explanation:
- State Management: We use the
useState hook from React to manage the currently selected item.
- Flexbox Layout: We use CSS Flexbox to create a two-column layout. The left column contains the list, and the right column displays the details.
- Event Handling: Clicking on a list item updates the
selectedItem state, which triggers the display of the corresponding item's details on the right side.
- Running the App:
Start the development server:
npm run dev
Visit http://localhost:3000 in your browser to see the app in action.
This setup provides a clean split between the list navigation and the detail display, which is suitable for various use cases, such as a simple item selection interface.