Hash Route Listener
ReactJS
Hard
7 views
Problem Description
Listen to hash changes and show the active section name.
Output Format
Render a React component.
Constraints
Use hashchange event and update state from window.location.hash.
Official Solution
import React, { useEffect, useState } from 'react';
function readHash() {
const h = (window.location.hash || '').replace('#', '');
return h || 'home';
}
export default function App() {
const [route, setRoute] = useState(() => readHash());
useEffect(() => {
function onHash() {
setRoute(readHash());
}
window.addEventListener('hashchange', onHash);
onHash();
return () => window.removeEventListener('hashchange', onHash);
}, []);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode hash route</h2>
<div style={{ display: 'flex', gap: 10 }}>
<a href='#home'>Home</a>
<a href='#topics'>Topics</a>
<a href='#practice'>Practice</a>
</div>
<div style={{ marginTop: 10, color: '#555' }}>Active: {route}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!