preact-router + hash history
by keemor
HTML
<script src="https://unpkg.com/preact"></script>
<script src="https://unpkg.com/preact-router"></script>
<script src="https://unpkg.com/[email protected]/umd/history.min.js"></script>
SCSS
body {
background: #FFF;
padding: 60px 10px;
}
header {
box-sizing: border-box;
position: fixed;
left: 0;
top: 0;
width: 100%;
background: #EEE;
padding: 10px;
border-bottom: 1px solid #AAA;
input {
box-sizing: border-box;
display: block;
background: white;
border-radius: 3px;
box-shadow: 0 0 0 .5px #888;
border: none;
font-size: 100%;
padding: 5px;
width: 100%;
outline: none;
}
}
Babel + JSX
const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
history.replaceState(0,0,'/'); // jsfiddle hax
const App = () => (
<div>
<AddressBar />
<Router history={createHashHistory()}>
<div path="/">
<p>
all paths in preact-router are still /normal/urls.
using hash history rewrites them to /#/hash/urls
</p>
Example: <a href="/page2">page 2</a>
</div>
<div path="/page2">
<p>Page Two</p>
<a href="/">back to home</a><br/>
</div>
</Router>
</div>
);
// this is just a fake address bar
class AddressBar extends Component {
componentDidMount() {
this.timer = setInterval( () => this.setState({}), 100);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<header>
<input readonly value={location.href.substring(location.origin.length)} />
</header>
);
}
}
render(<App />, document.body);