'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>
Solution 1:[1]
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>
)
Solution 2:[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";
Solution 3:[3]
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";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://github.com/facebook/create-react-app
Solution 4:[4]
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()}`);
Solution 5:[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>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tarreq |
Solution 2 | |
Solution 3 | adz5A |
Solution 4 | |
Solution 5 | alien_jedi |