Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding react to static html

I would like to add a React component in one of the divs from a static HTML page. I'm doing so instead of converting the entire page into React since I only need React for few parts of my web page. I followed the instructions on https://reactjs.org/docs/add-react-to-a-website.html. And my questions are:

  1. Is it okay to do that, or is it rather recommended that I implement my website entirely in React?
  2. I did what the aforementioned page told me, but the section I used React did not get implemented when I displayed it on my browser (my IDE is WebStorm). Is there a specific script (like yarn start when using React framework) that I have to run in order to compile?
like image 578
Paul Avatar asked Dec 31 '22 12:12

Paul


1 Answers

Checkout this minimal example. You need to include 3 scripts

  • react.development.js (the react lib)
  • react-dom.development.js (react lib to interact with dom)
  • babel.min.js (converts react JSX into browser compatible JS)

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        
        <!-- Don't use this in production: -->
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
      </head>
      <body>
        <div id="root"></div>
        <script type="text/babel">
          function HelloWorld(props){
            return <h1>{`Hello, world! ${props.name}`}</h1>;
          }
          ReactDOM.render(
            <HelloWorld name="James"/>,
            document.getElementById('root')
          );
    
        </script>
      </body>
    </html>

Note: this is a great way to try React but it's not suitable for production. It slowly compiles JSX with Babel in the browser and uses a large development build of React.

  • Read this section for a production-ready setup with JSX:
    https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project

  • In a larger project, you can use an integrated toolchain that includes JSX instead:
    https://reactjs.org/docs/create-a-new-react-app.html

  • You can also use React without JSX, in which case you can remove Babel: https://reactjs.org/docs/react-without-jsx.html

SOURCE : https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html

like image 136
Dehan Avatar answered Jan 03 '23 00:01

Dehan