Как из сайта html сделать react
Перейти к содержимому

Как из сайта html сделать react

  • автор:

Add React to a Website

React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Perhaps you only want to add some “sprinkles of interactivity” to an existing page. React components are a great way to do that.

The majority of websites aren’t, and don’t need to be, single-page apps. With a few lines of code and no build tooling, try React in a small part of your website. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.

Add React in One Minute

In this section, we will show how to add a React component to an existing HTML page. You can follow along with your own website, or create an empty HTML file to practice.

There will be no complicated tools or install requirements — to complete this section, you only need an internet connection, and a minute of your time.

Step 1: Add a DOM Container to the HTML

First, open the HTML page you want to edit. Add an empty <div> tag to mark the spot where you want to display something with React. For example:

We gave this <div> a unique id HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it.

Tip

You can place a “container” <div> like this anywhere inside the <body> tag. You may have as many independent DOM containers on one page as you need. They are usually empty — React will replace any existing content inside DOM containers.

Step 2: Add the Script Tags

Next, add three <script> tags to the HTML page right before the closing </body> tag:

The first two tags load React. The third one will load your component code.

Step 3: Create a React Component

Create a file called like_button.js next to your HTML page.

Open this starter code and paste it into the file you created.

Tip

This code defines a React component called LikeButton . Don’t worry if you don’t understand it yet — we’ll cover the building blocks of React later in our hands-on tutorial and main concepts guide. For now, let’s just get it showing on the screen!

After the starter code, add three lines to the bottom of like_button.js :

These three lines of code find the <div> we added to our HTML in the first step, create a React app with it, and then display our “Like” button React component inside of it.

There is no step four. You have just added the first React component to your website.

Check out the next sections for more tips on integrating React.

Tip: Reuse a Component

Commonly, you might want to display React components in multiple places on the HTML page. Here is an example that displays the “Like” button three times and passes some data to it:

Note

This strategy is mostly useful while React-powered parts of the page are isolated from each other. Inside React code, it’s easier to use component composition instead.

Tip: Minify JavaScript for Production

Before deploying your website to production, be mindful that unminified JavaScript can significantly slow down the page for your users.

If you already minify the application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in production.min.js :

If you don’t have a minification step for your scripts, here’s one way to set it up.

Optional: Try React with JSX

In the examples above, we only relied on features that are natively supported by browsers. This is why we used a JavaScript function call to tell React what to display:

However, React also offers an option to use JSX instead:

These two code snippets are equivalent. While JSX is completely optional, many people find it helpful for writing UI code — both with React and with other libraries.

You can play with JSX using this online converter.

Quickly Try JSX

The quickest way to try JSX in your project is to add this <script> tag to your page:

Now you can use JSX in any <script> tag by adding type=»text/babel» attribute to it. Here is an example HTML file with JSX that you can download and play with.

This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production. When you’re ready to move forward, remove this new <script> tag and the type=»text/babel» attributes you’ve added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script> tags automatically.

Add JSX to a Project

Adding JSX to a project doesn’t require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.

Go to your project folder in the terminal, and paste these two commands:

  1. Step 1: Run npm init -y (if it fails, here’s a fix)
  2. Step 2: Run npm install babel-cli@6 babel-preset-react-app@3

Tip

We’re using npm here only to install the JSX preprocessor; you won’t need it for anything else. Both React and the application code can stay as <script> tags with no changes.

Congratulations! You just added a production-ready JSX setup to your project.

Run JSX Preprocessor

Create a folder called src and run this terminal command:

Note

npx is not a typo — it’s a package runner tool that comes with npm 5.2+.

If you see an error message saying “You have mistakenly installed the babel package”, you might have missed the previous step. Perform it in the same folder, and then try again.

Don’t wait for it to finish — this command starts an automated watcher for JSX.

If you now create a file called src/like_button.js with this JSX starter code, the watcher will create a preprocessed like_button.js with the plain JavaScript code suitable for the browser. When you edit the source file with JSX, the transform will re-run automatically.

As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from its documentation.

If you notice that you’re getting comfortable with build tools and want them to do more for you, the next section describes some of the most popular and approachable toolchains. If not — those script tags will do just fine!

Как из сайта html сделать react

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 2 years ago .

I am building a MERN stack site, and wondering what would be the best way to convert this HTML template to a react site. Breaking down the template to components, adding routes manually, and converting HTML to JSX etc seems to be a tedious task.

The question arises because in themeforest, the most popular admin templates were built for a jQuery / HTML world, not for a full stack JS world. For example, the theme that I’ve linked above has

7000 downloads. These templates upon purchase give you a whole bunch of HTML and CSS, and if we have to build a react site out of these, then manually converting the HTML to JSX, and breaking it down to componenets, is a laborious process. Wondering if there’s a better approach to solving this problem.

How to convert HTML template into React Project

React is a popular JavaScript library now. It is mainly used to update the front view of the page only and it works faster than other website for using virtual DOM. How you can change the a HTML template into a react project and run from react server are shown in this tutorial. You have to download any free HTML template and create a fresh react app before starting this tutorial.

Steps:

1.The HTML template that I have used in this tutorial is downloaded from the following link. You can download it to use for your testing purpose.

2. I have created a new react app named reactapp. You can store the in any location of your drive. But I will apply mysql and PHP in my next tutorial, so I have stored the folder under htdocs folder. If you are new in react then you can click here to know the steps for installing reactjs.

3. Copy all the folders from the HTML template folder and paste in the public folder of reactapp folder.

4. Create a folder named pages under src folder of recatapp. You have to create necessary js files depends on the html pages contains in HTML template. I have used one page template here and there is only one html file in the template folder.

5. Open the index.html file from HTML template folder and copy the content inside <head> tag and paste the content inside the <head> tag of index.html file under public folder of reactapp.

6. Create a file named Home.js under src/pages/ folder. Copy the following content in the file.

7. Copy the content of <body> tag of index.html without script links from the template and paste inside the <div> tag of return() of Home.js file. Add the script link below the <body> tag of index.html of public folder.

8. Now, replace all <hr>, <br>, <img> and <input> tag by <hr/>, <br/>, <img/> and <input /> in Home.js file.

9. Open app.js file from the src folder and replace the code with the following code.

10. Run the react server and check the template is running as a react project.

Hope, you have converted the template successfully. In the next tutorial I will show how you can make this project dynamic by using PHP and MySQL.

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is a library that renders HTML strings into React components without using dangerouslySetInnerHTML . Converts standard HTML elements, attributes and inline styles into their React equivalents and provides a simple way to modify and replace the content.

This library is a hard fork of https://github.com/peternewnham/react-html-parser. It has some improvements and is converted to typescript.

It is important to understand that this library should not be used as a direct replacement for using properly sanitized HTML and that it only provides the same level of protection that React does which does not provide 100% protection. All HTML should be properly sanitized using a dedicated sanitisation library (such as dompurify for node/js) before being passed to this library to ensure that you are fully protected from malicious injections.

What doesn’t React protect me from?

Whilst React has a certain level of protection to injection attacks built into it, it doesn’t cover everything, for example:

  • xss via iframe src: <iframe src=»javascript:alert(‘xss’)» />
  • xss via link href: <a href=»javascript:alert(‘xss’)»>click me</a>

Click here to see these in action and how to protect yourself using dompurify in the browser.

Why doesn’t HTML to React protect me automatically?

Including a sanitizer as part of the library means it is making decisions for you that may not be correct. It is up to you to decide what level of sanitization you need and to act accordingly. Some users may already be sanitizing on the server or others may have specialized requirements that cannot be covered by a generic implementation.

Additionally, HTML sanitization is a hard thing to get right and even the most popular and actively developed sanitizers have vulnerabilities discovered from time to time. By leaving the sanitization outside of this library it gives users the ability to patch and deploy any fixes needed immediately instead of having to wait for a new version of this library to be released with the fix.

function convertHtmlToReact(html, [options])

Takes an HTML string and returns equivalent React elements

  • html : The HTML string to parse
  • options : Options object
    • decodeEntities=true (boolean): Whether to decode html entities (defaults to true)
    • transform (function): Transform function that is applied to every node
    • preprocessNodes (function): Pre-process the nodes generated by htmlparser2

    The transform function will be called for every node that is parsed by the library.

    function transform(node, index)

    • node : The node being parsed. This is the htmlparser2 node object. Full details can be found on their project page but important properties are:
      • type (string): The type of node (tag, text, style etc)
      • name (string): The name of the node
      • children (array): Array of children nodes
      • next (node): The node’s next sibling
      • prev (node): The node’s previous sibling
      • parent (node): The node’s parent
      • data (string): The text content, if the type is text

      return null Returning null will prevent the node and all of it’s children from being rendered.

      return undefined If the function does not return anything, or returns undefined, then the default behaviour will occur and the parser will continue was usual.

      return React element React elements can be returned directly

      Allows pre-processing the nodes generated from the html by htmlparser2 before being passed to the library and converted to React elements.

      • nodes : The entire node tree generated by htmlparser2 .

      The preprocessNodes function should return a valid htmlparser2 node tree.

      function convertNodeToReactElement(node, index, transform)

      Processes a node and returns the React element to be rendered. This function can be used in conjunction with the previously described transform function to continue to process a node after modifying it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *