Search code examples
reactjsreact-dom

How to pass arguments to functions in another file? - React 17.0.1


I have this file Foo.js:

const Foo= ({ someArg }) => {
  alert(someArg);
};

export default Foo;

I am calling it from App.js:

function App() {
  useEffect(() => {
    Foo("text");
  }, []);
...

The function gets called, but the alert shows undefined instead of the actual value that was passed. How do I properly pass arguments to a function in another file?


Solution

  • Problem is you are destructuring a string which doesn't have a property called someArg. That's why undefined is displayed.

    Correct Way:

    const Foo= (someArg) => { // No destructuring
      alert(someArg);
    };
    
    export default Foo;
    
    function App() {
      useEffect(() => {
        Foo("text"); // You are passing a string
    }, []);
    
    const Foo= ({ someArg }) => { // Doing destructuring
      alert(someArg);
    };
    
    export default Foo;
    
    function App() {
      useEffect(() => {
        Foo({someArg: "text"}); // You are passing an object
    }, []);
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment