Encountering an issue with importing external JavaScript files in the App.js file during React development

Currently, I am embarking on the development of a basic starter app that deals with SMTP anonymously in React. This project is primarily for educational purposes.

Prior to diving into actual development work, I have decided to keep things simple and focus on creating a basic script to ensure that the code functions correctly.

In my App.js file, I have a straightforward script that generates random keyword emails and allows users to copy the generated email address each time they refresh the page.

import logo from './logo.svg';
import './App.css';

const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) 
{
    let result = ' ';
    let addr = "@example.com";
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    result=result+addr;

    return result;
}

var mail=generateString(9)


function CopyIt() {
  
  var copyText = document.getElementById("evar");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}


function App() {
  return (
   <> 
   <pre>
   <h1>This is Temporarily mail site </h1>
   <p>It helps you Access your Anonymous mail without logins Required </p>
   </pre>
   <nav className="navbar navbar-light bg-light">
      <form className="container-fluid">
        <div class="input-group">
        <span class="input-group-text" id="basic-addon1">@</span>
        <input type="text" id="evar" class="form-control" value={mail} aria-label="Username" aria-describedby="basic-addon1"></input>
        <button onClick='Copyit()'>Copy text</button>
        </div>
      </form>
    </nav>

   </>
  );
}

export default App;

However, I encountered an issue where the previously generated email was copied every time I refreshed the main App.js file. To resolve this problem, I created a new JavaScript file named logic.js and moved both the generateStrings and CopyIt functions there.

I then imported the logic.js file into App.js:

import './logic.js'

Subsequently, my logic.js file looks like this:

const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateString(length) 
{
    let result = ' ';
    let addr = "@example.com";
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    result=result+addr;

    return result;
}


function CopyIt() {
  
  var copyText = document.getElementById("evar");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999);

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}

Upon running the code, I encountered errors stating that genrateStrings() and CopyIt() were not found. In an attempt to rectify this issue, I updated import './logic.js' in public/index.html and src/index.js as well.

Despite trying different methods, such as using

<ScriptTag type="text/javascript" src="logic.js" />
, none of them yielded the expected results mentioned in various tutorials I referred to.

As a beginner in React, I found it challenging to understand the complexities involved in importing external JS files and incorporating them seamlessly within my project.

Answer №1

Don't forget to properly export your functions from logic.js

export function createNewArray...

export function manipulateData...

Here's how you should import them in MainApp.js

import { createNewArray, manipulateData } from './logic.js';

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

Position the Bootstrap button on the right side

this is the code I am working with: <p class="h1 p-3 mb-2 bg-danger text-white text-danger">Lagerbestand unter Mindestmenge! </p> <br /> <div class="border text-center"> <p class="h5 text-center">Durc ...

Retrieve fresh information whenever there is a modification in the component's properties

I am looking for a solution to refresh a component every time it is called. I have 4 buttons that trigger the display of different data in the component when clicked. Upon clicking the button for the first time, the constructor and componentWillMount() fu ...

What is the process for requiring web workers in npm using require()?

I have a setup using npm and webpack, and a part of my application requires Web Workers. The traditional way to create web workers is by using the syntax: var worker = new Worker('path/to/external/js/file.js'); In my npm environment, this metho ...

Tips for displaying extensive outcomes on the react interface?

My current setup involves a React frontend, an Express backend, and a PostgreSQL database. I am facing an issue while trying to render large JSON objects containing approximately 8000 rows. The site performs well with fewer than 1000 records, but as the nu ...

Getting event properties in a React component using the rest operator: A comprehensive guide

Can someone please assist me? I am new to TypeScript and struggling with how to use event props in my component. I have defined two props and need all my events as rest props. I encountered an error when trying to use my component with onClick event. The ...

Using jQuery to locate the href attribute within a TD element with a specific

Update URL <td class="posts column-posts"><a href="edit.php?tshowcase-categories=ops&amp;post_type=tshowcase">2</a></td> Current URL: <span class="view"><a href="https://blog.company.com/team/tshowcase-categories/ops ...

Having trouble with installing redux using npm?

When I try to run npm install redux, an error occurs: npm ERR! fetch failed https://registry.npmjs.org/lodash-es/-/lodash-es-4.6.0.tgz npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404 It seems there might be a pr ...

Resize the shape of an image's polygon

Is there a way to independently scale a specific polygon of an image on hover? For example, I have a world map and I would like to enlarge a country when hovering over it, then return it to its original size when no longer hovering. I am familiar with us ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

Fetching data from MySQL using Ajax technology

I need assistance with my form that is supposed to input a name and phone number, fetch data from a MySQL database based on the input values, and display the results. However, when I execute the query using an onclick function, instead of retrieving data f ...

Achieve perfect vertical alignment for a set of three identical boxes using CSS media queries

Bootstrap is being used and the goal is to align three boxes of the same height vertically. https://i.stack.imgur.com/8xg0g.png Currently, the three blocks are not of equal height and do not occupy maximum space. Some manual padding has been added to addr ...

Tips for creating a responsive container for mobile and smaller devices using Bootstrap 3

Apologies in advance for the lengthy post, but I welcome any suggestions and ideas. Thank you! I'm facing an issue with my layout breaking when the screen size is below 1200px (images and text drop down). I don't mind if they stack vertically on ...

Manipulating JSON Objects in AngularJS

While I may be proficient in utilizing existing data, my expertise in editing JSON objects is not quite up to par yet. Any assistance in this area would be greatly appreciated. This question may seem basic, but I am seeking clarification as I am unsure. H ...

Retrieving specific object properties within an Angular 2 and Ionic 2 form

Within the @Page, I have a few select inputs. In addition to storing the value of the selected option, such as {{project.title}}, I also require the ability to return another selected object property, such as {{project.id}} or even the entire object. When ...

Sequelize error: Foreign key mentioned, yet not found in the table

I recently started using Sequelize and have been relying heavily on the documentation available here. The documentation mentions the importance of using hasOne(), hasMany(), and belongsTo() to automatically add foreign key constraints. In my case, I am wor ...

What is the process of inserting information into a nuxt-link in nuxt.js?

I am currently facing an issue with passing data into nuxt-link. Whenever I click on the link, nuxt-link returns a 404 error and fails to load the file. However, the other two links that use :href and hardcoding seem to be working fine. <template> ...

Arrangement with mutual prime numbers and rowspan

I have a set of unique data points (A, B1, B2, C1, C2 and C3) that I want to organize into a table layout as shown below: +----+----+----+ | | B1 | C1 | | +----+ | | A | B2 +----| | +----+ C2 | | | B3 | | +----+----+----+ After trying ...

How can I use absolute positioning and scrolling with an Iframe?

One of the key elements of this website is the implementation of iframes, with only one displayed at a time. However, my current issue revolves around the inability to scroll within these iframes due to their absolute positioning. I have attempted variou ...

After an extended wait, the npm create-react-app process remains unfinished

Can anyone help me figure out why 'npm create-react-app' is not finishing on my Windows computer? It always gets stuck like this and never completes the installation, even after waiting for hours. C:\Users\Best\Desktop>npx creat ...

Update the file path in the asset-manifest.json file

For my experiment with Azure DevOps, I decided to work on a ReactJS project that I found at https://github.com/alik0211/pokedex. The project runs smoothly when I build it locally and use npm start in the build folder. One of the files is located at http:// ...