Skip to content Skip to sidebar Skip to footer

How To Import Function From Another File Into Reactjs Component?

I have a main.js file function convertToFahrenheit(param) { return param * 2 + 30; } function convertToCelsius(param) { return (param - 32) * 1.8; } I have imported it i

Solution 1:

Try this

exportfunctionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

exportfunctionconvertToCelsius(param) {
    return (param - 32) * 1.8;
}

and then in your component

import { convertToCelsius } from "../assets/js/main.js";

Solution 2:

You need to export the functions in main.js and then use the correct syntax to import them to the component. Try this:

exportfunctionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

exportfunctionconvertToCelsius(param) {
    return (param - 32) * 1.8;
}

Then for importing do the following

importReactfrom"react";
importTemperatureInputfrom"./TemperatureInput.js";
import { convertToFahrenheit, convertToCelsius } from"../assets/js/main.js";

This site goes into more detail about it: https://www.geeksforgeeks.org/reactjs-importing-exporting/

Solution 3:

Use export in main.js

exportfunctionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

and named import

import {convertToFahrenheit} from "../assets/js/main.js";

Solution 4:

There are multiple ways you can get function by using ES6 import and export syntax

In short, export allows you to export multiple expressions at a time while export default only allows one expression to be exported. Also, for those things exposed by export, brackets are needed when import while export default doesn't.

Option 1: export by named import

exportfunctionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

exportfunctionconvertToCelsius(param) {
    return (param - 32) * 1.8;
}

//imported in your needed fileimport {convertToFahrenheit, convertToCelsius} from'../assets/js/main.js'

Option 2: another way using export by name import

functionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

functionconvertToCelsius(param) {
    return (param - 32) * 1.8;
}

export {convertToFahrenheit, convertToCelsius}

//imported in your needed fileimport {convertToFahrenheit, convertToCelsius} from'../assets/js/main.js'

Option 3: export default for one expression (function, class, object, array...)

//demo for exporting 1 functionexportdefaultfunctionconvertToFahrenheit(param) {
    return param * 2 + 30;
}

//imported in your needed file, the name can be customised by you.import myOwnFunc from'../assets/js/main.js'

Post a Comment for "How To Import Function From Another File Into Reactjs Component?"