How can I use a function from another file in react?

I would like to create a file (function.js) for a function that does this:

let i = 0; if (this === that) { i = 0; } else { i = 1; } 

I would then like to add it to (this.js)

import function from "./function"; class Example extends Component { state = { test }; render() { function() return ( <div> <h1>{this.state.test.sample[i].name}</h1> </div> 
2

5 Answers

You can do something like:

function.js

const doSomething = function() { let i = 0; if (this === that) { i = 0; } else { i = 1; } } export default doSomething; 

App.js (for example):

import doSomething from "./function"; class Example extends Component { state = { test }; render() { doSomething() return ( <div> <h1>{this.state.test.sample[i].name}</h1> </div> ) 
2

there are multiple ways to do it.

1st

If you are going to create multiple functions in that file

export const one = () => { let i = 0; if (this === that) { i = 0; } else { i = 1; } } export const two = () => { let i = 0; if (this === that) { i = 0; } else { i = 1; } } 

And then import and use it

import { one, two } from "./functions" 

2nd

You can use export defualt

export default = function() { let i = 0; if (this === that) { i = 0; } else { i = 1; } } 

and then simply use it by doing this

import function from "./function"; 
2

The function keyword is a reserved identifier.

On the browser you need some kind of bundler tool which will allow to import from a js module. On the server you can just require(path/to/file). I suggest you look at create-react-app for a fully functionnal react setup. The basic setup contains example about the JS module system (see docs below).

In return your file needs to export the symbols you want to use.

In a directory with a.js and b.js where b wants to import a symbol from a

// file a.js export function myFunction () {} // file b.js import { myFunction } from "./a"; 

Export your function like this in function.js

export function funcName() { //function stuff let i = 1; return i; } 

the import would be

import { funcName } from './function'; console.log(`value of i is ${funcName()}`); 
5

function.js has below code

const funcName = function() { let i = 0; if (this === that) { i = 0; } else { i = 1; } } export default funcName; 

And you can use it in this.js as below -

import funcName from "./function"; // or wherever the file is saved class Example extends Component { state = { test }; render() { funcName(); return ( <div> <h1>{this.state.test.sample[i].name}</h1> </div> ); } 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like