Small Router Without Library
ReactJS
Hard
6 views
Problem Description
Create a tiny router that switches pages using state and buttons.
Output Format
Render a React component.
Constraints
No react-router. Use state to switch pages.
Official Solution
import React, { useState } from 'react';
function Home() {
return <p>Welcome to meetcode.</p>;
}
function Topics() {
return <p>Browse topics: HTML, CSS, React.</p>;
}
function Practice() {
return <p>Pick one question and solve it.</p>;
}
export default function App() {
const [route, setRoute] = useState('home');
const Page = route === 'topics' ? Topics : route === 'practice' ? Practice : Home;
return (
<div style={{ padding: 16 }}>
<nav style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
<button type='button' onClick={() => setRoute('home')} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Home</button>
<button type='button' onClick={() => setRoute('topics')} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Topics</button>
<button type='button' onClick={() => setRoute('practice')} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Practice</button>
</nav>
<Page />
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!