Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use preact using html and script tag?

Tags:

preact

I have a very simple react program that imports react using a script command and a cdn.

How do I covert it to preact while keeping the same structure?

I tried to follow these instruction, but they weren't very clear

<!DOCTYPE html>
<html>
<head>
    <title></title>
<script src="https://unpkg.com/react@15/dist/react.js"> </script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/babel.js"></script>
</head>
<style type="text/css">

</style>
<body>
    <div id='root'></div>
    <script type="text/babel">
function T(props){
  return <h1>{props.title}</h1>
}
ReactDOM.render(<T title='welcome'/>,document.getElementById('root'))

    </script>

</body>
</html>
like image 320
yigal Avatar asked Sep 01 '25 02:09

yigal


1 Answers

As per this github issue you have a couple of different options for using Preact with a script tag. You can directly call h- Preact's version of React.createElement or you can use babel standalone to transform your JSX as you were in your original React example. Here is a Preact conversion of your original example.

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/preact/7.2.0/preact.js"></script>
  <script src="https://unpkg.com/[email protected]/babel.js"></script>
</head>
<body>
  <div id='root'></div>
  <!-- option 1: alias it -->
  <script>window.React = { createElement: preact.h }</script>
  <script type="text/babel">
    function T(props){
      return <h1>{props.title}</h1> 
    }
    preact.render(<T title="Welcome" />, document.getElementById('root'));
</script>
</body>
</html>
like image 169
Conor Cussell Avatar answered Sep 05 '25 11:09

Conor Cussell