Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem while exporting a function from another file in React

I've defined a function in a file but when I export and try to access the return value, I got an undefined error.

Here is my function:

export default function produits(){
  return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]
}

When in the other file I do

import {produits} from './mesprod.js

and i don't know why i get that error. But i've just tried to change the export line of my function by removing default keyword then everything goes fine. So what is the difference between

export default function functionName()

and export function functionName()

and

export default function()

and i dont really understand the use of { } when importing a module although i use it all the time.I'm a beginner in React js

like image 971
Christian Lisangola Avatar asked Sep 22 '26 18:09

Christian Lisangola


1 Answers

When you do export default

You should import it like

  import produits from './mesprod.js'

Because only one can be exported by default per module so it will be imported like above

When you need to use curly brackets

Say suppose you are exporting one function using default and other two without default

mesprod.js

   export default function produits (){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

   export function produits1(){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

   export function produits2(){return [{nom:"chaussure",prix:45}, {nom:"polo",prix:8}]}

So while importing you do like below

  import produits, { produits1, produits2 } from './mesprod.js'

Curly braces are used when you export multiple functions without default keyword and if you export with default then import it without curly braces

like image 93
Hemadri Dasari Avatar answered Sep 25 '26 10:09

Hemadri Dasari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!