Getting started with Preact : helloworld standalone example

Preact looks to be the most closest React alternative in terms of code similarity. There official motto: "Fast 3kB alternative to React with the same ES6 API". You almost have to change nothing in the codes if you look to switch your React application to Preact. Lets have a quick look at a simplest Preact standalone helloworld component example with JSX/babel embedded in single html page, the very 'clock' example in their documentation :

  1. <html>
  2. <head></head>
  3. <body>
  4. <div id="abcd"></div>
  5. <script src="https://npmcdn.com/preact@2.8.3/dist/preact.js"></script>
  6. <script src="https://npmcdn.com/preact-compat@0.6.1/preact-compat.js"></script>
  7. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
  8. <script>
  9. window.React = preactCompat;
  10. window.ReactDOM = preactCompat;
  11. </script>
  12. <script type="text/babel">
  13. const { h, render, Component } = preact; // normally this would be an import statement.
  14. class Clock extends Component {
  15. constructor() {
  16. super();
  17. // set initial time:
  18. this.state.time = Date.now();
  19. }
  20. componentDidMount() {
  21. // update time every second
  22. this.timer = setInterval(() => {
  23. this.setState({ time: Date.now() });
  24. }, 1000);
  25. }
  26. componentWillUnmount() {
  27. // stop when not renderable
  28. clearInterval(this.timer);
  29. }
  30. render(props, state) {
  31. let time = new Date(state.time).toLocaleTimeString();
  32. return <span>{ time }</span>;
  33. }
  34. }
  35. render(<Clock/>, document.getElementById('abcd'));
  36. </script>
  37. </body>
  38. </html>

Reference: