Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include custom JS files in to React create app

I had js files under public folder i want to include these js files in to react components which are under src component folder in react create application?

like image 930
Venkateswararao Avatar asked Jun 07 '17 07:06

Venkateswararao


People also ask

Where do I put JavaScript code in React?

To add JavaScript code inside JSX, we need to write it in curly brackets like this: const App = () => { const number = 10; return ( <div> <p>Number: {number}</p> </div> ); }; Here's a Code Sandbox Demo. Inside the curly brackets we can only write an expression that evaluates to some value.

Can we use js file in React?

React Hooks and other methods For features used across the application, we can simply add JS files to head using the <script> tag in our global index.


2 Answers

Please read Using the public Folder.

In general we recommend installing packages from npm and using import to access them from the source. But if you must use a prebuilt JS file that you don’t want to import, you can add it to the public folder (for example, public/mylib.js) and then add this to public/index.html:

<script src="%PUBLIC_URL%/mylib.js"></script>

Then you can access the global variable from your app, for example:

const mylib = window.mylib;

And then use it.

Hope this helps!

like image 117
Dan Abramov Avatar answered Oct 03 '22 12:10

Dan Abramov


Put them in the same folder as your react components and simply import them to you react components like so:

// importing your js file called jslibrary.js
// make sure that the file path is correct!
import { function1 } from './jslibrary.js'

You also have to make sure that you are exporting your function / variables in your jslibrary file, like so:

export function function1() {
  //... do stuff
}

let myVar = 1234;
export myVar;

If you use export default on a function or a variable, you don't need to use the brackets like in the above.

For more info, I highly recommend the documentation on import and export.

like image 35
Mμ. Avatar answered Oct 03 '22 10:10

Mμ.