For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentSteps to Add React to a Website

Steps to Add React to a Website

Published
12th Oct, 2023
Views
view count loader
Read it in
7 Mins
In this article
    Steps to Add React to a Website

    React allows you to quickly develop complex user interfaces and web applications by breaking them down into simple and manageable components. Tailormade for today’s ever-evolving world, React JS is one of the most sought-after web frameworks among industries and is a key component of their growth.    

    Note: This article is purely for beginners and hence the following process is NOT recommended for production sites. However, this will allow the reader to get a taste of React without delving into toolchains and complicated processes.  To learn more about Full Stack Developer courseenroll in leading KnowledgeHut web development courses.   To learn more about usereducer in React, click here. 

    Before getting into the article, let's read about what is markdown, why it's important, best practices, and more.  

    All of you are already aware of ReactJs Javacript Library, designed by Facebook, which is a popular open-source JavaScript library. It is used for writing rich and engaging frontend abstractions in fewer lines of code within a short time. One of the reasons why React is so popular is because of its rendering performance.    

    In this post, we will learn how to add React JS to our current website. This article will pave the way for you to quickly start coding with React JS or simply import React in your existing project. 

    No, it’s not rocket science! You can simply add it in your html file, that too in 1 minute!  

    What, just 1 minute? As in, 60 seconds…..? 

    Read on to know more! 

    Add React in One Minute 

    An essential simple website consists of 3 files: 

    • Html file 
    • Js file, and 
    • CSS file  

     React JS can be used in a normal index.html file with no npm or web-packs. Hard to believe?  

    Steps to Add ReactJs to an Existing Website:  

    Let’s not waste any more time and start editing our existing HTML page, which is called index.html. There is no requirement of any external libraries or any other tool, just a code editor, website folder holding all the above files and Internet Connection.  

    Step:1 Open the HTML file you want to edit and add a div on which you want to add the React implementation. 

    For instance: (index.html) looks like this, see line number 12-13

    <!DOCTYPE html> 
    <html> 
      <head> 
        <meta charset="UTF-8" /> 
        <title>Steps To Add React to a Website </title> 
      </head> 
      <body> 
      
        <h2>Steps To Add React to a Website </h2> 
      
        <!-- We will put our React component inside this div. → Line 12 
    
        <div id="some_random_id"></div> 
      
      </body> 
    </html>

    Provide a unique ID attribute to the div, as shown above. This will allow us to distinguish it from the element we want to implement.  

    Step:2 Add the Script Tags to the same HTML page before the </body> tag as shown below: 

    (Same as above) 
    ... 
        <!-- To load React add the scripts. --> 
        <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> 
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> 
     
      </body> 
    </html>

    Here, we have added the scripts to load/import the React library.  

    Step:3 Now add one more script, to load our component which is “some_random_id” in the above code. Let’s name the JS file as “my_component.js”. 

    <!DOCTYPE html> 
    <html> 
      <head> 
        <meta charset="UTF-8" /> 
        <title>Steps To Add React to a Website </title> 
      </head> 
      <body> 
     
        <h2>Steps To Add React to a Website </h2> 
        <div id="some_random_id"></div> 
     
        <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> 
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> 
     
        <!-- To Load our React component. --> 
        <script src="my_component.js"></script> 
     
      </body> 
    </html>

    Step:4 Now, Create and open the file named my_component.js and paste the following code:  

    'use strict'; 
    const e = React.createElement; 
    class myButton extends React.Component { 
      constructor(props) { 
        super(props); 
        this.state = { isliked: false }; 
      } 
     
      render() { 
        if (this.state.isliked) { 
          return 'Yes I Really Like This.'; 
        } 
     
        return e( 
          'button', 
          { onClick: () => this.setState({ isliked: true }) }, 
          'Like Button' 
        ); 
      } 
    } 
    const domContainer = document.querySelector('#some_random_id'); 
    ReactDOM.render(e(myButton), domContainer);

    Here we have created React component named myButton, and displayed a button inside it. 

    Step:5 ???

    Step:6  ???

    No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too. 

    No step 5 or 6! It’s done. React has been  successfully added to the project and you can check the output too.

    Adding JSX in Our Components

    React is added, now let’s jump to writing code in an easier manner.  

    Consider the following snippet: 

    const element = <h1>Hello, Buddy!</h1>;

    What does this syntax look like? It’s neither a string nor an HTML. This is JSX, a simple extension to JavaScript. While it’s not mandatory to use JSX with React, most of the developers find it helpful while experimenting with UI. You will experience this yourself later. Worried where to start your web designing career? Enroll in Training in Web Design.  

    Let’s quickly try JSX

    JSX comes with full power, as of JavaScript. We will see this later. Let’s get started on JSX by simply adding the below script tag:

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

    Or you can also use JSX by adding type="text/babel" in any <script> tag.

    Add JSX to our Project

    Adding JSX to the project is more like adding some preprocessors for which we really need to install Node. If it’s already installed, then ignore this step and if it’s not, then:

    Install Node from here

    Check if Node is successfully installed by quickly running the following command in the terminal:

    node -v

    And it should give some output as:

    v8.11.4

    Note: Version may be less than 8.11.4. 

    Great, let’s move ahead and add JSX to our project: 

    1. Head to your website folder in the terminal: 

    1. Run npm init -y 

    1. Run npm install babel-cli@6 babel-preset-react-app@3 (NPM is used here to install JSX preprocessor) 

    Done?  Let’s Run it! 

    Running JSX Preprocessor  

    1. Go to the same website folder in terminal 
    2. Create a folder named src 
    3. Go inside src in the terminal and run the following command:  
    npx babel --watch src --out-dir . --presets react-app/prod
    

    Move the file “my_component.js” to the src folder and the watcher will convert the preprocessed file to basic Javascript file which is readable for the browser.  

    If you want to play around these preprocessors, head over here. 

    Simple Example to See JSX: 

    Let’s say we have a variable called title, we will see how we can use it in JSX: 

    const title = 'React Developer';

    In JSX, we use by wrapping it in curly braces as {title}

    const title = 'React Developer'; 
    const element = <h1>Welcome, {title}</h1>; 
      
    ReactDOM.render( 
      element, 
      document.getElementById('root') 
    );

    AJAX and APIs Call-in React For Our Component    

    React doesn’t have any inbuilt package for calling the API calls, as it is a standalone library that comes only with fetch() method. But while working on Web projects, we need to render data somehow, either by local data or from server data. 

    There are plenty of libraries by which we can make API calls, and we can choose any of them depending upon our project. Some of them are 

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

    Let’s go ahead with basic simple and index(0)th option, which is Fetch.  Trust me, you can choose any of them! 

    Using Fetch to Make HTTP Calls in React 

    Fetch() is a modern method and a browser-based API which is commonly used to make HTTP calls. The standard syntax of the Fetch API looks like: 

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

    Here, API_URL is the URL using which we want to fetch the data from the server, and the URL comes with other arguments also depending upon the type of request (GET, PUSH, PUT,.. etc). 

    Unlock Your Potential with our Computer Programming Course - Learn the Art of Coding and Master the World of Technology. Enroll Today!

    The API returns with a promise which gets resolved into the response object once the response is fetched from the server. 

    async getNames() { 
        // Calling some additional headers 
        const response = await  
        // Dummy API Data 
    fetch("https://jsonplaceholder.com/users", { 
          method: "GET", // *Type of request GET, POST, PUT, DELETE 
          mode: "cors", // Type of mode of the request 
          cache: "no-cache", // options like default, no-cache, reload, force-cache 
          headers: { 
            "Content-Type": "application/json" // request content type 
          }, 
          credentials: "same-origin", // options like include, *same-origin, omit 
          redirect: "follow", // manual, *follow, error 
          referrerPolicy: "no-referrer", // no-referrer, *client 
          // body: JSON.stringify(data) // Attach body with the request 
        }); 
     
        this.setState({ names: await response.json() }); 
      } 

    Here we have called a function named getNames, which fetches the data along with other parameters like: 

    • Method: what type of HTTP call is there, 
    • Header: to define request headers for authorization or content 
    • Mode: defines the type od mode, cors or no-cors,  

    As per official documentation: 

    (Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.) 

    Read about CORS here  

    • Body: to send some additional data to the server as a request body 

    Based on the requirement, we can call the desired options. And we can also use catch for managing errors while making API calls. 

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

    This is how we can use Fetch to make API calls, and do further operations in React.

    Unleash your inner data wizard with our exclusive Data Science Bootcamp! Become a sought-after data scientist and unlock endless career opportunities. Join now!

    Conclusion

    In this article, we learned how to add a React component in an HTML file or an existing website. You can follow the same steps to your own website, or if you want to have a fresh start you can simply create an empty HTML file to get started with React. We also saw how we can use JSX in our project and also played around with basic Http calls in React. 

    I hope this article was helpful in getting started with React.  

    Happy Learning!

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon