How To Import Function From Another File Into Reactjs Component?
Solution 1:
Try this
export function convertToFahrenheit(param) {
return param * 2 + 30;
}
export function convertToCelsius(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:
export function convertToFahrenheit(param) {
return param * 2 + 30;
}
export function convertToCelsius(param) {
return (param - 32) * 1.8;
}
Then for importing do the following
import React from "react";
import TemperatureInput from "./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
export function convertToFahrenheit(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
export function convertToFahrenheit(param) {
return param * 2 + 30;
}
export function convertToCelsius(param) {
return (param - 32) * 1.8;
}
//imported in your needed file
import {convertToFahrenheit, convertToCelsius} from '../assets/js/main.js'
Option 2: another way using export
by name import
function convertToFahrenheit(param) {
return param * 2 + 30;
}
function convertToCelsius(param) {
return (param - 32) * 1.8;
}
export {convertToFahrenheit, convertToCelsius}
//imported in your needed file
import {convertToFahrenheit, convertToCelsius} from '../assets/js/main.js'
Option 3: export default
for one expression (function, class, object, array...)
//demo for exporting 1 function
export default function convertToFahrenheit(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?"