Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading