Reputation: 229
I've been studying React for a while and just now started developing my own apps with it when i noticed i don't really know the difference between the react
and react-dom
libraries, i know that 'react' is the JavaScript library and react-dom
is the library which provides methods for me to interact with the DOM, but nothing seems to happen when i don't import them (i use the create-react-app environment so that could be it). That being said, here's how i normally create a component:
import React from 'react';
function ComponentName () {
return(
<div>
<!-- Component code -->
</div>
)
}
export {ComponentName};
So what's the difference between the code on top, this:
import React from 'react-dom';
function ComponentName () {
return(
<div>
<!-- Component code -->
</div>
)
}
and this?
import React from 'react-dom';
function ComponentName () {
return(
<div>
<!-- Component code -->
</div>
)
}
Upvotes: 0
Views: 228
Reputation: 1074148
Create React App handles using react-dom
for you (in index.js
/index.ts
in the src
directory).
Import React
from "react"
, not from "react-dom"
. If you're using the a recent version, you only need to do this if you're using the React
object in your code (for instance using React.memo
, although you could use import {memo} from "react"
instead). You no longer need to import React
just for JSX (details).
Basically:
"react"
is the main library"react-dom"
provides features for using React with the DOMUpvotes: 1
Reputation: 568
React
For React, you must import React from 'react'. You need to import the default, and you need to name it React. This is because anytime you write JSX code like or , this JSX code is transpiled and uses React.createElement(). So, you need to have access to the React object as it is named.
NOTE: React 17 and some older specified major versions now include a new JSX transform that does not require this explicit React import.
ReactDOM
For ReactDOM, however, you are probably mostly concerned with the DOM-related methods that are part of the default export, methods like render() or hydrate(). Because that's what you'll probably be using, you can name your import module anything you want. So, you could do something like this:
import FooBar from 'react-dom'
FooBar.render(someElement)
This does work, but the standard convention is to call the imported module ReactDOM, as that would make your code more understandable to anyone else looking at it.
Upvotes: 1