Guide on incorporating a JS file in a React application

I recently obtained a template for my website that includes the following JS file which is being called from my React component.

!(function($) {
  "use strict";

  // Hero typed
  if ($('.typed').length) {
    var typed_strings = $(".typed").data('typed-items');
    typed_strings = typed_strings.split(',')
    new Typed('.typed', {
      strings: typed_strings,
      loop: true,
      typeSpeed: 100,
      backSpeed: 50,
      backDelay: 2000
    });
  }

  // Smooth scroll for the navigation menu and links with .scrollto classes
  $(document).on('click', '.nav-menu a, .scrollto', function(e) {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      e.preventDefault();
      var target = $(this.hash);
      if (target.length) {

        var scrollto = target.offset().top;

        $('html, body').animate({
          scrollTop: scrollto
        }, 1500, 'easeInOutExpo');

        if ($(this).parents('.nav-menu, .mobile-nav').length) {
          $('.nav-menu .active, .mobile-nav .active').removeClass('active');
          $(this).closest('li').addClass('active');
        }

        if ($('body').hasClass('mobile-nav-active')) {
          $('body').removeClass('mobile-nav-active');
          $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
        }
        return false;
      }
    }
  });

  // Activate smooth scroll on page load with hash links in the url
  $(document).ready(function() {
    if (window.location.hash) {
      var initial_nav = window.location.hash;
      if ($(initial_nav).length) {
        var scrollto = $(initial_nav).offset().top;
        $('html, body').animate({
          scrollTop: scrollto
        }, 1500, 'easeInOutExpo');
      }
    }
  });

  // ...

})(jQuery);

After pasting the HTML file into my component and importing all CSS and JS files, I encountered an error in the JS file.

The error messages are as follows: Line 7:1: Expected an assignment or function call and instead saw an expression no-unused-expressions Line 14:9: 'Typed' is not defined no-undef Line 25:9: Unexpected use of 'location' no-restricted-globals Line 25:85: Unexpected use of 'location' no-restricted-globals Line 183:5: 'AOS' is not defined no-undef Line 193:4: 'jQuery' is not defined no-undef

Could someone please advise on how to properly import this JS file into my React component?

Thank you in advance.

Answer №1

When incorporating scripts into a React component, it's important not to simply import one that has been downloaded from external sources and utilizes tools like jQuery or Owl Carousel.

Instead, seek out existing React components that replicate the functionality of the script or create your own custom components to utilize within your React application.

Answer №2

It is important to note that inserting raw JS / jQuery code directly into a React component may not function as expected. Explore alternative, more "React-like" approaches for accomplishing your goals. It's likely there are existing libraries designed to handle similar tasks you're interested in :)

Consider researching a React-specific library focused on animating various elements. From what I gather, this appears to be the functionality you are striving for.

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

Filtering ng-repeat in AngularJs based on nested data properties

Within my data tracking appointments, I have information on months, weeks, days, and timeslots. When it comes to the listing view, displaying "weeks" is unnecessary (although important for other reports). To eliminate days without appointments, I can use ...

resolving conflicts between Rails and JavaScript assets

Currently, I am facing an issue with two gems that provide JavaScript assets as they are conflicting with each other. The conflicting gems in question are the lazy_high_charts gem and the bootstrap-wysihtml5-rails gem. Initially, I only had the bootstrap ...

Tips for resolving jQuery conflict problems

I am dealing with a jQuery issue where I have two scripts - one for the slider and the other for a dropdown menu. When I remove one script, the slider works but the dropdown doesn't, and vice versa. I have looked at tutorials online on how to resolve ...

Tips for showcasing the currently active item in a Bootstrap dropdown menu using jQuery

I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it d ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

Learn how to separate strings within an object and add them to an array with JavaScript!

When I receive an object, the quantity of strings differs each time and varies. Object { key_id: 7, key1: "String1, String2", key2: "String1, String2, String3", key3: "String1, String2", key4: "String1, String2"; … } I am lo ...

Tips for customizing the height of the select component in React Material UI

Currently, I am working on a select component that has a fixed height which cannot be decreased. You can see the screenshot below: The issue I am facing is that I want the height of the Select component to match that of the Autocomplete component, specifi ...

Issue with integrating leaflet-geotiff library in a React application

Currently, I am attempting to integrate leaflet-geotiff into my react application. Even though I have followed all the steps outlined in the documentation, I keep encountering an error with L.leafletGeotiff(), which provides the following feedback: Line 2 ...

Attempting to position text both vertically and horizontally at the center beside an image

Visit my GitHub page here! Hello, I'm new to asking questions but I need help centering the text "Welcome to my site" both horizontally and vertically. I want it positioned halfway between the image and the right margin. I tried using display flex bu ...

Production environment encountering a 404 error from API

I am currently working on a next.js application and I am facing an issue with setting up an API. Interestingly, when I run the app in development mode, the APIs get called successfully. However, if I try to run it using next start, I encounter a 404 error ...

The backend API does not receive the correct value from the checkbox

I'm having an issue with my registration page in ReactJS. There is a checkbox field called isadult. After clicking on the Register button and saving the data to a MongoDB database, the value of isadult shows up as [Object object] instead of True or Fa ...

Is there a way to selectively display only the first 100 lines using console.log()?

Is there a console.log equivalent of .head() in JavaScript? I need to display only the first 100 lines of a response on my terminal without the top part being cut off due to the entire object being printed. Any suggestions on how to achieve this? ...

To fill the remaining white space, add an underline after the last line of text

I'm struggling to implement a SCSS/CSS styling concept where I need to add a solid line before or after the last line of a heading. The challenge is that the width of the last line varies based on the screen size. I am open to any suggestions. Here&a ...

CSS can always surprise with its unexpected animations

Currently developing a static website with CSS animations: * { -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease- ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

How can I prevent the expansion of elements in a drop-down menu when using display:

I've been struggling to implement a drop-down feature in my menu. The issue is that when I use display: flex, hovering over the drop-down also expands all other boxes without drop-downs. Any ideas on how to fix this easily? Additionally, is there a w ...

Most effective method to access deeply nested values and set defaults

How can I optimize the retrieval of deeply nested defaults? At the moment, I'm employing this code snippet to access the bucket value of check_ab and assigning it a default value of 'A', but this approach is impacting readability: setting ...

Web design featuring an aesthetic reminiscent of an open folder on an iPhone

I'm struggling a bit and could really use some assistance. I've been searching for a long time but can't seem to figure out how to create an iPhone folder-like design for the web. The design should have that "slide out" effect when you click ...

Click a button to spin images around

Is there a way to rotate an image by 90 degrees, 180 degrees, and 360 degrees with the click of a button? <img class="test" id="image" src="images/image" alt="This is the Display Image" /> I attempted to use the following script, but was not satisf ...