Created
February 14, 2019 13:28
-
-
Save viniciusCamargo/efcdb50e37c5a67870d1965c05673d43 to your computer and use it in GitHub Desktop.
Preact without JSX + lifecycle methods
This file contains hidden or 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
<!-- Reference: https://github.com/developit/preact-without-babel/ --> | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<style> | |
#header { | |
opacity: 1; | |
transition: opacity 1s; | |
} | |
#header.fade { | |
opacity: 0; | |
} | |
</style> | |
<script> | |
window.__INITIAL_STATE__ = { hideHeader: false, removeHeader: false }; | |
</script> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script src="https://cdn.jsdelivr.net/npm/preact/dist/preact.min.js"></script> | |
<script> | |
const { Component, h, render } = window.preact; | |
const ANIMATION_TIME = 1000; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = __INITIAL_STATE__; | |
} | |
componentDidMount() { | |
this.setState({ message: 'Hello!' }); | |
setTimeout(() => { | |
this.setState({ hideHeader: true }); | |
}, ANIMATION_TIME); | |
} | |
componentDidUpdate() { | |
if ( | |
this.state.hideHeader === true && | |
this.state.removeHeader === false | |
) { | |
setTimeout(() => { | |
this.setState({ removeHeader: true }); | |
}, ANIMATION_TIME); | |
} | |
} | |
render(props, { message, hideHeader, removeHeader }) { | |
return h( | |
'div', | |
{ id: 'app' }, | |
removeHeader ? null : h(Header, { message, hideHeader }), | |
h(Main) | |
); | |
} | |
} | |
const Header = ({ message, hideHeader }) => { | |
return h( | |
'header', | |
{ id: 'header', className: hideHeader ? 'fade' : null }, | |
h('h1', null, 'App'), | |
message && h('h2', null, message) | |
); | |
}; | |
class Main extends Component { | |
componentDidMount() { | |
console.log('hello'); | |
} | |
render() { | |
const items = [1, 2, 3, 4, 5].map((item, id) => | |
h('li', { id }, 'Item ' + item) | |
); | |
return h('main', null, h('ul', null, items)); | |
} | |
} | |
render(h(App), document.getElementById('app')); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment