简体   繁体   中英

Is there a way to use my JS files in React? Export or script tags etc?

I have a JS file which makes some elements appear/disappear on mouseenter/click. This works fine in normal JS. I am now building my app using React, but I can't get this functionality. I have tried export / import as you can see, and script:src in my index.html .

// Options appear on hover
export const optionsBtn = document.querySelector("[data-function='options']");
export const hiddenButtons = [...document.querySelectorAll(".hidden")];

export function optionsHover() {
  hiddenButtons.forEach(button => button.classList.toggle("hidden"));
}

optionsBtn.addEventListener("mouseenter", optionsHover);
optionsBtn.addEventListener("click", optionsHover);

Unsure as to how I'd get this code to work in React. Am I missing something here?

This is not the ideal approach . However if you want to use that, here's the work around:

  1. Convert your JS code into a simple JS class in your React App
  2. Create class's instance (object) in the respective React component
  3. Bind the events of the React component with the said object's function

This would be sufficient to use your existing JS within the React App.

NOTE

Its not best practice. DOM should not be manipulated directly when using reactJS, you should not do that ideally, as react takes care of DOM manipulation and it is highly optimised for that.

If you have to use your JS and rewriting it using React Component is not an option,

You can import your script using require('yourfile.js') but since your JS is trying to access dom elements you would want to execute the JS after the dom elements are rendered.

You can do this by requiring the yourfile.js from the componentDidMountlifecycle method of your root app component.

Below is an example,

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

let myjs;

class App extends Component {
  constructor() {
    super();
  }

  componentDidMount() {
    myjs = require("./yourfile"); // Import file here after component mounted
    myjs.optionsHover();
  }

  render() {
    return (
      <div>
        <div>
          <button data-function="options">Option</button>
          <button class="hidden">Button</button>
          <button class="hidden">Button</button>
          <button class="hidden">Button</button>
          <button class="hidden">Button</button>
          <button class="hidden">Button</button>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Here is a full snippet .

you can try import 'yourfile.js' or require('your js file')

const myScript = require('script')

then myScript.something()

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