简体   繁体   中英

How to add an external javascript file into a react component

I have a react component (jsx) which shows a forum and few images, I have also a button who shows a popup or modal but this popup is programmed with JavaScript in an external file.
I want to load this code into my component.
I used a script tag and didn't work. any ideas? this is my external JavaScript file:


let popup = document.getElementById('popup');
let modalContainer = document.getElementById('modal-container');
let buttonTarget = document.getElementById('button-target');
let cross = document.getElementById('cross');


buttonTarget.addEventListener('click', openModal);
cross.addEventListener('click', closeModal);

   function openModal() {
    popup.style.display = 'block';
    modalContainer.style.display = 'block';
  }

  function closeModal() {
    popup.style.display = 'none';
    modalContainer.style.display = 'none';
  }


React is also Javascript (jsx is another way/syntax of writing javascript code which then transpiles to javascript) so You can use any javascript file within it. In order to do that first check that javascript file exports what You want to use in Your react component then check if You imported it in the file which holds react component.

It can could be done adding <script> tag in your html. But javascript code which manipulates DOM isn't advised to be used along with React. Also Modals or Popups can easily handled by react state. And you can find several libraries as well. for ex, https://www.npmjs.com/package/react-modal

Lets Say Your External JS file is Temp.js containing the following piece of code or a function.

export function foo(){
 //some code here}

For meeting the current situation you move|copy that file to same folder where your component is

now simply add this to your component

import {foo} from "./temp";

here you go you have imported the file

Now How to use that as it is the function

so call this as simply foo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM