How To Add React To Existing Project Or Website?

CMS Vs LMS: a developer is working with a CMS

React is the most popular JavaScript framework on the planet. You can use it to quickly create feature-rich web applications. Also, it enables you to easily add new features to your existing project, like React image upload. You just need to type a few lines of code. It can make your life a lot easier. But how can you add React to existing project? What are the steps? In this post, you will find all the details.

Is it really easy to add React to existing project?

Yes, you can easily add React to your existing application. The process is very simple.

In this post, you will find the way of adding a React component to an existing HTML page. You can follow the same method to add it to your your own website. Alternatively, you can create an empty HTML file to practice.

Add React to Existing Project: Equipment Needed

  • First, you need to have Node installed on your PC. You can get it from nodejs.org. You need to have at least Node version 10.
  • Next, you need to have the node package manager (npm). It gets automatically installed on your PC with Node. The npm version needs to be 5.2 or higher.
  • Finally, you need to have a good code editor. There are plenty of solutions available on the market. For example, Visual Studio Code is an intuitive editor. It is massively popular among developers. You can download it from here.

Add React to Existing Project or Website

In this section, you will add a React component to modify an existing HTML page of your website. Here are the steps:

Step 1: Adding DOM Container To The HTML

First, open the HTML page that you want to change. Create an empty div element. This is the area where you will use React to display the changes.

<div id="medium_blog_container">
<!-- Here we will mount our component -->
</div>

Step 2: Add The Script Tags Or React Tags

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

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

Step 3: Create A React Component

Now, you have to create a JS file, called medium_post_component.js, next to your HTML page.

You can write React either with JSX or without JSX. The example shown above is without JSX. It can directly run on the browser.

Take a look at these two lines:

With these two lines, you are looking for the <div> that you added in the first step. Then you display the “Like” button React component inside of it.

Add React to Existing Project – Add JSX To A Project

You don’t need to use complicated tools, like a bundler or a development server, for adding JSX to a project. In fact, it’s quite similar to adding a CSS preprocessor. However, you must have Node.js installed on your PC. It’s the only requirement.

The process of adding JSX is very simple. You just need to follow these steps:

1. First, Go to your project folder in the terminal.

2. Now, run the following command

npm init -y 

3. If the above command fails, run this command:

npm install babel-cli@6 babel-preset-react-app@3

That’s it! You have successfully added a production-ready JSX setup to your project.

Read: Future-Proofing Your React File Uploader

Add React to Existing Project – Run JSX Preprocessor

To run JSX preprocessor, you have to create a folder, called “src.” Then run this command in the terminal:

npx babel --watch src --out-dir . --presets react-app/prod

Tip: Are you seeing an error message that says “You have mistakenly installed the babel package”? You might have missed the previous step. Try performing it in the same folder. It should fix the issue.

You don’t have to wait for the process to finish. The aforementioned command initiates an automated watcher for JSX.

If you create a file, called like_button.js in the src folder, the watcher will create a preprocessed like_button.js file. It will have the plain JavaScript code suitable for the browser.

Also, it allows you to utilize modern JavaScript syntax features. For example, you can use classes without worrying about breaking older browsers.

Keep in mind that npx is not a typo. It’s a package runner tool that comes with npm 5.2+.

Read: Greetings Apps With React

Add React to Existing Project – AJAX And APIs Call-in React For Component    

There are tons of libraries for making API calls. However, these are the most popular ones are:

  • Fetch
  • Axios
  • React-Axios
  • Use-Http
  • React-request and more

Add React to Existing Project – Using Fetch To Make HTTP Calls in React 

Fetch() is a browser-based API. You can use it to make HTTP calls. Let’s take a look at the standard syntax of the Fetch API.

let response = fetch(
    API_URL,
    .... (some more options)
);

Here, you are calling a function, named getNames. It fetches the data. Also, it fetches other parameters. like:

  • Method: It helps you to determine what type of HTTP call is there
  • Header: It enables you to define request headers for authorization or content
  • Mode: Mode defines the type of mode, cors or no-cors
  • Body: You can use it to send additional data to the server as a request body

Here is an example of using Fetch in React:

async getName(){
  //With .then and .catch section
  let response = await fetch("https://jsonplaceholders.com/users")
  .then(resposne => {
    return response.json();
  this.setState({ names:response })  
  })
  .catch(error => {
    console.log(error);
  });
}

Tips for Adding React to Existing Project

Reuse a Component

You might want to display React components in multiple places on an HTML page. To do it, you have to follow these steps:

1. Go to your HTML file. Then add these lines:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <p>
      This is the first comment.
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="1"></div>
    </p>

    <p>
      This is the second comment.
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="2"></div>
    </p>

    <p>
      This is the third comment.
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="3"></div>
    </p>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="like_button.js"></script>

  </body>
</html>

2. Go to your JavaScript file. Insert this code:

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return 'You liked comment number ' + this.props.commentID;
    }

    return e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'Like'
    );
  }
}

// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container')
  .forEach(domContainer => {
    // Read the comment ID from a data-* attribute.
    const commentID = parseInt(domContainer.dataset.commentid, 10);
    const root = ReactDOM.createRoot(domContainer);
    root.render(
      e(LikeButton, { commentID: commentID })
    );
  });

Source Code:

You can view the source code right here.

Keep in mind that the approach is useful when the parts of the page are isolated from each other. But inside React code, you should use component composition. Because it’s easier to use.

Read: Components Of Next JS Image

Minify JavaScript for Production

Unminified JavaScript can significantly impact page speed. It will frustrate the users. That’s why you need to minify JavaScript before deploying React apps. It will boost the loading speed and user experience.

Have you already minified your application scripts? Have you ensured that the deployed HTML load the versions of React ending in the production.min.js file? If it’s done, your site is production-ready.

<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>

If you don’t have a minification step for your scripts, you can set it up by following these steps:

1. First, you have to install Node.js

2. Then run the following command in your project folder:

npm init -y

3. Next, run this command:

npm install terser

4. Finally, it’s time to minify a file. If you want to minify a file, called like_button.js, simply run this command in the terminal:

npx terser -c -m -o like_button.min.js -- like_button.js

You will see the creation of a new file, called like_button.min.js. It will contain all the minified code.

Quickly Try JSX

You can quickly try JSX in your project by adding the following <script> tag to your page:

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now, you can start using JSX in any <script> tag. You just need to add type=”text/babel” attribute to it.

Here is an example of an HTML file with JSX:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/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 MyApp() {
        return <h1>Hello, world!</h1>;
      }

      const container = document.getElementById('root');
      const root = ReactDOM.createRoot(container);
      root.render(<MyApp />);

    </script>
    <!--
      Note: this page 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
    -->
  </body>
</html>

Introducing Filestack’s React SDK

filestack-react is a wrapper on filestack-js sdk. It allows you to integrate with Filestack service in just a few lines of code. You can utilize it to significantly improve the look and performance of your file uploader.

How can I use Filestack’s React SDK in my application?

1. First, you have to install Filestack’s React SDK with this command:

npm install filestack-react

2. Next, you can insert filestack-react into your app.

import { PickerOverlay } from 'filestack-react';

<PickerOverlay
  apikey={YOUR_API_KEY}
  onSuccess={(res) => console.log(res)}
  onUploadDone={(res) => console.log(res)}
/>

3. You can use it to effortlessly add various functionalities. For instance, you can render a basic drop pane picker by using this line:

<PickerDropPane apikey='YOUR_APIKEY'/>

You can use Filestack to easily enable file uploading in React. You can find the details right here.

Conclusion

In this article, you have learned to add React to existing project. Also, you have known useful tips, like reusing components and minifying JavaScript for production. Now, you can start leveraging React and easily add amazing features to your existing projects.

Add React to Existing Project – FAQ

What is a React component?

The components are one of the core building blocks of React. They are independent and reusable bits of code. They enable you to easily build UIs for your application.

How can I create react app with npx?

You can create react app with npx by using this command: “npx create react app”.

What is React in coding?

React is an efficient and flexible JavaScript library. It enables you to easily build complex user interfaces by using small and isolated pieces of code, called “components”.

Sign up free and experience the best file uploading solutions for your web applications today with Filestack.

Read More →

Ready to get started?

Create an account now!