skip to Main Content

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


  1. Some sample code would help, but I’m guessing your talking about something like this:

    App.js

    ...
    
    return (
      <Title />
    )
    

    Title.js

    ...
    
    function Heading() {
      return <h1>HelloWorld</h1>
    }
    
    export default function Title() {
      return (
        <>
          <Heading />
          <p>Some text</p>
        </>
      )
    }
    

    If I’m understanding your question correctly, you’re wondering how App.js knows about Heading, inside Title.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 what Title.js is returning. It calls Title.js, and will display whatever it returns. Inside Title.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, to App.js, and everyone is happy.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search