Last active
December 30, 2017 11:43
-
-
Save petja/0d8b0d0e0d3487287e3fb759be44d50a to your computer and use it in GitHub Desktop.
Yksinkertainen demo routeavasta React-softasta
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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