Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 257
user10916917 Avatar asked Jan 15 '19 12:01

user10916917


People also ask

How do I export and import functions in React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.

How do you call a method from another class in React JS?

To call a method from another class component in React. js, we can pass the class method as a prop to a child component. We have components Class1 and Class2 . And Class1 is a child of Class2 .

How do you call js file in React?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.


Video Answer


1 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>
     )
like image 55
Tarreq Avatar answered Oct 10 '22 23:10

Tarreq