Upon returning to a page in react, the script failed to load

This is the code that I am currently using: The script is placed within the navbar and on the home page. The navbar script displays all the time, but the script on the home page does not load when navigating from one page to another.

import '../App.css';
import './hero.css'
import Hero_Img1 from '../images/blob-haikei (2).png'

function HeroSection() {

  

  return (
    <div className='hero-container'>
      <div className="hero_img_container">
      <img src={Hero_Img1} className="hero_img_left" alt="Hero img"/>
      </div>
      <h1>The White Dental</h1>
      <p>We Care For You</p>
     
 <script type='text/javascript' src='https://www.lybrate.com/***/****/****/em-wt.js'></script>
  <div className='lybrate-widget' name='dr-sandeep-kumar-jangra-dentist' tabs='ba,cp' btn-text=' Book Appointment '></div>
    </div>
  );
}

export default HeroSection;

Answer №1

If you need to dynamically load a script, you can achieve it in the following way:

useEffect(() => {
    loadScript('https://www.example.com/***/****/****/custom-script.js');
    loadScript('dynamic-script.js');
    loadScript('www.someotherwebsite.com/script.js');    
}, [])


const loadScript = (src) => {
    let script = document.createElement('script');
    script.src = src;    
    document.body.append(script);
}

Answer №2

If you want to incorporate external scripts into your React application, consider utilizing custom react hooks.

import { useEffect } from 'react';

const useExternalScript = url => {
  useEffect(() => {
        const script = document.createElement('script');
        script.src = url;
        script.async = false;
        document.body.appendChild(script);

// Remove the appended script when the component unmounts.
        return () => {
            document.body.removeChild(script);
        }
    }, [url]);
};

export default useExternalScript;


// Import and implement the hook in components as needed.
import useExternalScript from './useExternalScript';
import React from 'react';

function App() {
useExternalScript('path_to_script_file');
  return (
    <></>
  );
}

export default App;


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

Issues related to the performance of React, Redux, and three.js

UPDATE: After identifying the issue, I have narrowed it down to this small gist and this jsfiddle. In my real-time 3D game based on three.js, I intended to utilize Redux for state management. Despite creating a simple prototype for testing purposes, even ...

Does React Fiber belong to the core of React, or is it considered as a distinct entity?

After delving into the older React documentation on React Core, I find myself in a state of confusion. The React core solely consists of the necessary APIs for defining components. It does not encompass the reconciliation algorithm or any platform-specif ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

In a JavaScript array of objects, the Vuetify select :items feature allows you to assign an id and name to each object. When a name is selected, the corresponding id is automatically

I am currently working with an array of objects that contain both an id and a name property: Teams [ { id: 1, name: 'team1' }, { id:2, name: 'team2' } ] Is there a way to dynamically pass the names as items in a vuetify selec ...

The CSS box's height should be determined dynamically

Is there a way to create a div with a maximum width of 200px and have the height increase automatically as needed? Can someone assist me with which CSS properties to use? My goal is to keep the width of the box constant while ensuring that any text inside ...

Enhance the functionality of a directive by incorporating the ui-mask directive

Recently, I implemented a custom directive for an input field that adds a calendar icon with a datepicker to the input. I have used this directive in various sections of my application and now I am interested in incorporating ui-mask - another directive I ...

How can I transform area, city, state, and country into latitude and longitude using Google Maps API v3?

Is there a way to retrieve the latitude and longitude for a string that includes area name, city name, state name, and country name using Google Maps API V3? ...

How can a groovy script help in extracting the Version Number using Parse()?

Seeking guidance on parsing a version number using a groovy script When extracting a payload from Ariba, encountering an issue with the ItemNumber field Initially, it parsed as a float, but now returning a version instead Struggling to update this part ...

Storing a blob on the server?

I have a program that can extract metadata from sound files. If the sound file contains an album image, I am able to convert it into a blob object URL and use it locally. However, I am struggling with saving this blob image to the server. Currently, I ha ...

Using ng-repeat to pass a parameter into a function triggered by ng-click

Check out the code snippet provided: <div> <div class="list-group"> <a class="list-group-item" ng-click="c.selectItem(note.sys_id)" ng-repeat="note in data.notes"> <h4 class=& ...

Is there a way to customize the design of an HTML scrollbar to resemble the one often seen on Google search engine result pages

While casually browsing online, I stumbled upon something truly unique. The image below shows a Google search result in Firefox that I have never encountered before or since. This screenshot captured a search result that was scrollable within itself. Isn& ...

What is the best way to remove an item from a mongoose schema and then update the document or schema?

I'm encountering an issue with deleting items from an array that is nested inside the User schema. When attempting to save the document, I receive the following error message? Here is the error: TypeError: User.save is not a function at C:\U ...

The Select2 choices are not being updated correctly

I am in the process of implementing a feature on my website that allows users to select a Country -> State -> City. The state and city select boxes are initially set to disabled, and when a user chooses a Country, it should display the corresponding ...

SyntaxError: VM3419:1 - Unexpected token "<" was not caught

I'm exploring AJAX techniques in a demo project where I retrieve data from the server using AJAX methods. However, I encountered the following error: " Uncaught SyntaxError: Unexpected token< xhr.onreadystatechange @main.js" JS: (function ...

Adjusting the width of a div using CSS and HTML across different resolutions

Need help with cutting a PSD file into CSS and HTML. The issue is the container with background image has a width of 1160px, which may cause it to be hidden on smaller resolutions. The main content container has a width of 996px, so that aspect is good. I ...

A single pre-task to handle multiple tasks within the package.json file

Currently, I am implementing Terraform for a specific project and I have been assigned two tasks within my package.json file. These tasks involve executing the commands terraform plan and terraform apply. "scripts": { "tf:apply": "terraform apply", ...

Deactivate a button based on a comparison condition

How can I prevent a button from being clickable when a specific condition is met? I attempted to do it this way, but it seems to be ineffective: <button type="text" disabled="{{candidature.statusCandidature.libelle == 'En cours' }}" >edit ...

Mastering GraphQL querying in React using TypeScript

After successfully setting up a graphql and being able to use it in Postmen, here is how it looks: query listByName($name: String!) { listByName(name: $name) { id name sortOrder } } My variable is defined as {"name&quo ...

Analyze React.js source code for errors, instead of focusing solely on the DOM manipulation aspect

Can breakpoints be set in React.js code and debugged in the actual script rather than just in compiled javascript? For example: var HelloMessage = React.createClass({ render: function() { return <div>Hello {this.props.name}</div>; // ...