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!

4
  • Possible duplicate of using brackets with javascript import syntax Commented Jul 11, 2017 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. Commented Jul 11, 2017 at 10:00
  • @TadeášPeták That's exactly what I thought, just needed some confirmation. Thanks! :) Commented Jul 11, 2017 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. Commented Apr 27, 2018 at 15:40

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

1 Comment

import { Component } from 'react' is not destructuring. It is a named import.
0
import {Component} from 'react';

This is called named module import.

The module to import from. This is often a relative or absolute path name to the .js file containing the module, excluding the .js extension. Certain bundlers may permit or require the use of the extension; check your environment. Only single quotes and double quotes Strings are allowed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.