Skip to content

Instantly share code, notes, and snippets.

@petja
Last active December 30, 2017 11:43
Show Gist options
  • Save petja/0d8b0d0e0d3487287e3fb759be44d50a to your computer and use it in GitHub Desktop.
Save petja/0d8b0d0e0d3487287e3fb759be44d50a to your computer and use it in GitHub Desktop.
Yksinkertainen demo routeavasta React-softasta
import React from 'react'
import ReactDOM from 'react-dom'
import getViewFromURL from './routes.jsx'
class App extends React.Component {
state = {
view: null,
};
// componentDidMount on Reactin "taikafunktio" jota kutsutaan automaattisesti kun komponentti on läntätty DOM:iin
componentDidMount() {
// Kuuntele käyttäjän back- and forward-nappien painelua, ja renderöi
// view sen mukaisesti
window.addEventListener('popstate', function() {
this.setState({
view : getViewFromURL(),
});
});
// Huomaa myös lisätä tämä, jotta sulla on joku view joka renderöityy silloinkin
// kun käyttäjä tulee ekaa kertaa sun sivulle, eikä ole navigoinu minnekään
this.setState({
view : getViewFromURL(),
});
}
render() {
return (
<div id="main">
{this.state.view}
</div>
);
}
}
// Softa ladattu
window.addEventListener('DOMContentLoaded', function() {
ReactDOM.render(<App />, document.getElementById('ilmera-app'));
});
import FrontPage from './views/FrontPage.jsx'
import UserPage from './views/UserPage.jsx'
import NotFoundPage from './views/NotFoundPage.jsx'
export default function getViewFromURL() {
const userPageMatched = location.href.match(/^\/user\/(\d+)$/);
if (frontPageMatched) {
return <FrontPage />
} else if (userPageMatched) {
return <UserPage userId={userPageMatched[1]} />
} else {
return <NotFoundPage />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment