I can see there are two different ways to import:
import React from 'react' import { render } from 'react-dom'
The second one has brackets. What is the difference between the two? And when should I add brackets?
{} is used when you want to import part of an object. The * as searchView one will import all properties and methods in the searchView file.
In javascript code 2. In javascript code, curly brackets are used to deconstruct an object. “Now what does this really mean ?” Deconstruction is the process of assigning the items in an object to a constant or variable quicker.
The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. You need them when you want to use a JavaScript expression like a variable or a reference inside JSX.
Basically the curly braces {} are the another way for creating objects in javascript. This is equivalent to the "new Object()" syntax. Follow this answer to receive notifications.
Well, the difference between whether you should import your components within brackets or without it lies in the way you export
it.
There are two types of exports
A component can have one default export and zero or more named exports.
If a component is a default export then you need to import it without brackets.
E.g.,
export default App;
The import it as
import App from './path/to/App';
A named export could be like
export const A = 25;
or
export {MyComponent};
Then you can import it as
import {A} from './path/to/A';
or
import {A as SomeName} from './path/to/A';
If your component has one default export and few named exports, you can even mix them together while importing
import App, {A as SomeName} from './path/to/file';
Similarly in case of react
and react-dom
, React
and ReactDOM
are default exports
respectively whereas, for instance Component
is a named export
in react
and render
is a named export in react-dom
. That's the reason you can either do
import ReactDOM from 'react-dom';
and then use
ReactDOM.render()
or use it like mentioned in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With