I am exporting default function from JS file in React to App.js. This function calls another function inside, that was declared in its corresponding file but was not exported. How React knows where to get this function? Does export also exporting all dependencies of this function?
Trying to understand how export and import works.
3
Answers
Some sample code would help, but I’m guessing your talking about something like this:
App.js
Title.js
If I’m understanding your question correctly, you’re wondering how
App.js
knows about Heading, insideTitle.js
. This is one of the great things about React and other frameworks that allow us to make our apps composable, or in other words, able to break into small pieces.In short,
App.js
technically doesn’t know anything about Heading. All it cares about is whatTitle.js
is returning. It callsTitle.js
, and will display whatever it returns. InsideTitle.js
, we reach the<Heading />
tag, which grabs what that function is returning since it’s in scope. This gets returned, along with the extra paragraph, toApp.js
, and everyone is happy.The code, @Ryan provided won’t actually run unless you have a parent wrapper in Title. Also, React has a concept called Higher Order Components, which basically encapsulates all the dependencies each function needs which is why you don’t have to import ‘circular’ dependencies. https://legacy.reactjs.org/docs/higher-order-comp
In JavaScript(and React), when you export a function or any other entity (such as a variable or class) from a module using the export keyword, only the explicitly exported entities are made available for import in other files.
JavaScript doesn’t automatically export all dependencies or internal functions when you export a function or component. Only the explicitly exported entities are accessible from other files.
JavaScript knows where to find the exported function based on the import statement and the module path provided in the import statement.
When the export function is called and it calls the internal function, JavaScript will find the dependency from it’s module and run it. The internal function which is unexported, remains private to the module and cannot be accessed from outside.
This should be some help for you.
https://www.digitalocean.com/community/tutorials/understanding-modules-and-import-and-export-statements-in-javascript