0

Why does the below react work? As the function name in Hello.js component is Hello but it was not mentioned in main component that imported the Hello.js , Is it a property of arrow function-(if i use normal function instead of arrow function the programme show error.)

The Hello.js component :

import React from 'react';
const Hello =() => <h1> HELLO <h1/>
export default Hello

Where Hello.js component got exported/ been Called.

import React from 'react';
import MyComponent from './Hello'
class App extends React.Component{
   render(){
     return(
            <div>
               <MyComponent />
            <div/>
           );
      }
 }
Yoki
  • 5
  • 2
  • 3
    You have lots of typos in your code. `hello` is not the same as `Hello`, and `form` is not the same as `from`. I'm surprised your code works at all. – Andy Jul 17 '22 at 12:59
  • Why using class components when functional components are recommend since react 16.8? – sm3sher Jul 17 '22 at 18:00
  • My friendly Programmers , i have used class component instant of functional component as a part of learning process. @sm3sher , – Yoki Jul 18 '22 at 06:10

1 Answers1

2

This is called default export, you can name the component as you want when you import it.

But if you are using named export.

Ex:

export const something = 'something'

When you import it, you need to destruct the same name.

import { something } from 'file/path'

As @Felix, mentioned, you can give to named export another name ( in case there are naming conflicts )

Ex:

import { something as somethingElse } from 'file/path'

For more resources.

difference between named export and default export

Mina
  • 14,386
  • 3
  • 13
  • 26
  • 1
    Worth mentioning that you can still give it another name: `import { something as somethingElse } from 'file/path'`. – Felix Kling Jul 17 '22 at 13:10
  • @FelixKling, Yes, thanks for mentioning that, I will update the answer. – Mina Jul 17 '22 at 13:11
  • Thank you for mentioning and contributing your answer , please do validate my question. In Hello.js component i have uesed a arrow function for your referance. Yes, it is a default export but at the sametime if you are using a normal function in Hello.js you import by its on function name that is Hello else it shows error.@Mina pls contribute valid answer for right questions and try out the codes and get to a conclusion . ```import React from 'react'; function Hello(){return(

    HELLO

    )} export default Hello```(For educational perposes use this as Hello component and see the result.)
    – Yoki Jul 18 '22 at 08:39