N
N
nathan1117772019-06-17 19:43:28
JavaScript
nathan111777, 2019-06-17 19:43:28

What is {Component}? And what is it for in a particular example?

Websites say:
import React from 'react';
That is, we import the React object from the React library
. I saw an example where the code is written like this:
import React, {Component} from 'react';
What is {Component} ? And what is it for?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2019-06-17
@nathan111777

This is called named export. The twist is that React only has a default export.
The question is - how does it work then if it is named export, and React only has default?
The answer is that React is shipped as a CommonJS version, not an ESModule.
You can see in the sources that everywhere at the end is written "module.exports = React"
https://unpkg.com/[email protected]/index.js
https://unpkg.com/[email protected]/cjs/ react.development.js
https://unpkg.com/[email protected]/cjs/react.productio...
Then the magic happens (probably webpack), and it turns out that the default export is additionally duplicated by named exports.
See an example: https://codesandbox.io/embed/charming-wilbur-b6fwo
I write React everywhere and advise everyone.
And about "less characters":

// 70 chars
import React from 'react';
export class Foo extends React.Component {};

// 79 chars
import React, { Component } from 'react';
export class Foo extends Component {};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question