36

I just got in a project on React Native, where I constantly see classes extending both React.Component and Component itself.

Examples:

class SomeView extends React.Component

or

class OtherView extends Component

in both of them we are importing React, {Component} from React

Is there any actual difference, if so, which one? Didn't found any info on the web. Cheers!

jbarradas
  • 2,031
  • 3
  • 17
  • 22
  • Possible duplicate of [using brackets with javascript import syntax](https://stackoverflow.com/questions/31096597/using-brackets-with-javascript-import-syntax) – Mayank Shukla Jul 11 '17 at 10:00
  • 14
    When you do `import { Component } from 'react'`, you are importing `React.Component`. Meaning that if you, at the beginning of the file, write `import React, { Component } from 'react'`, `React.Component` refers to the exact same class as `Component`, making both syntaxes you mentioned valid. – Tadeáš Peták Jul 11 '17 at 10:00
  • @TadeášPeták That's exactly what I thought, just needed some confirmation. Thanks! :) – jbarradas Jul 11 '17 at 10:02
  • There is actually a difference. You may have multiple packages that export a Component. So, extending from React.Component makes clear and explicit which component is being used. – giorgosp Apr 27 '18 at 15:40

2 Answers2

24

Well you can do whatever you want really.

Doing import { Component } from 'react' is effectively the same thing as React.Component.

The import { Component } from 'react' syntax is called a Named Import

The import statement is used to import bindings which are exported by another module.

import defaultExport from "module-name";
import * as name from "module-name";
import { export } from "module-name";
import { export as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
João Cunha
  • 9,929
  • 4
  • 40
  • 61