What is the difference between createRoot and ReactDOM.render - javascript

What is the difference between ReactDOM.render and createRoot which is introduced in React18?

When rendering a React component to the DOM, the methods createRoot and ReactDOM.render are both used, but they differ in a few ways.
The conventional technique for rendering a React component to a particular DOM element—typically the root of your app—is ReactDOM.render. Consider this:
ReactDOM.render(<App />, document.getElementById('root'));
In this instance, the <App/> component is being rendered to the <div id="root"></div> element on the page.
createRoot : In order to render components in a new way with better performance and better support for concurrent mode, React 17 introduced a new method called createRoot. The fundamental operation of createRoot is similar to that of ReactDOM.render, except that it creates a new root container and returns a reference to it rather than rendering to a particular DOM node. Then, you can render your components to the root container using the returned reference. For instance:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
In conclusion, the primary distinction between createRoot and ReactDOM.render is that createRoot generates a new root container for rendering components, whereas ReactDOM.render renders components directly to a given DOM element.

Related

How to use React in multiple places in a normal website

I have a new website which isn't a single page app but a server rendered website (asp.net using Umbraco CMS). I used to use Angular 1.x in my websites, which is easy because you just load it in with script tags and the code is uncompiled.
I have been using React recently in SPAs started with create-react-app which looks after webpack, babel etc. for you and produces a single bundle. However, I want to use React in several places on the website like the main header/menu, contact forms etc so it makes sense to produce multiple bundles, although these bundles may share imports (Moment.js, Formik etc.).
There are instructions on the React website showing how to include a single script and attach it to an element in yourwebsite, but no complex examples.
So, how do I go about setting up something that will transpile everything without duplicating code in bundles. Do I need some kind of master bundle loaded on all pages and individual bundles for things like a contact form?
Secondly, how do I wire everything up? In an SPA you just have a root node and bind your app to the root node using react-dom, but if you've got mini pieces of react functionality littered through your app then do you need some kind of master script to bind everything to the right elements?
Any help would be greatly appreciated, even if it's just pointing me in the direction of some kind of boilerplate project.
Oh, and I'm not interested in doing a server side rendered Next JS app or anything like that, I think that could get too complicated to integrate with the CMS.
I think you can make a single bundle, rendering multiple component to different places. I created a little example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Body</h1>
</div>
);
}
function Footer() {
return (
<div className="App">
<h1>Footer</h1>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
const footerElement = document.getElementById("footer");
ReactDOM.render(<Footer />, footerElement);
You can play with it in this sandbox example. https://codesandbox.io/s/34nvv4nvy5
In addition to the answer above you can exclude React, ReactDOM or/and React Router (and any other dependencies) from your bundles and include them on the page so you aren't bundling them X amount of times. This way you can have separate entry files for each application.
webpack.config.js
externals: {
'react': 'React',
'react-dom': 'ReactDOM',
}
index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js" integrity="sha256-JBRLQT7aJ4mVO0H2HRhGghv/K76c5WzE57wW0Flc6ZY=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/cjs/react-dom.production.min.js" integrity="sha256-j2ERTIovDFVe0R+s0etuSiBQ2uxrNE6q0ow/rXxHvLA=" crossorigin="anonymous"></script>
If you want to render elements "outside" your root element of the react application, then you can use react Portals. We are using this approach as well and it's going well.
If you still think you want multiple mini react applications that run on the same page, you can communicate with them with the help of ReactDOM.render. Basically, ReactDOM.render can get invoked multiple times, it won't re-mount the entire application but instead will trigger updates and diffing to the react tree (same as a normal render method of components).
In fact, i wrote an article with a tutorial on how to Integrate React with other applications and frameworks.
I also tried to simulate this approach with a codesandbox example
Hope that helps.

How to add/use React component in only one part (cart page) of my existing node project?

Up until now I have been using create-react-app to build React applications and components.
However, I have a project that I'm working on which was built in node using pure JS for Dom manipulation and I wanted to add react to one page only (the cart page).
All tutorials I had watched assume you are starting project from scratch and I can't seem to figure out how to add React to just a single part of my project.
Can someone point me in the right direction?
I would recommend you start here:
https://reactjs.org/docs/rendering-elements.html
The React Docs actually also point at this tutorial for a non 'create-react-app' tutorial: https://blog.usejournal.com/creating-a-react-app-from-scratch-f3c693b84658
This is the React Docs for rendering elements. The TLDR version:
In your HTML file, where you want your React component to go, create an empty div and give it a unique name (i.e. 'app' or 'react-component')
Then create your component, etc. and have ReactDOM render on the unique id name.
To get it to render, in your node app, point it at the build path, typically bundle.js
I have got this working and managed to use React components (written in JSX) for specific parts of my custom JavaScript app (bundled via Webpack). You basically need three things.
1) Your custom JavaScript app
// MyApp.js
import { renderMyReactComponent } from "./MyReactComponent.jsx";
class MyApp {
// Call this when you want to show your React component
showMyReactComponent() {
// Create an empty div and append it to the DOM
const domElem = document.createElement("div");
domElem.classList.add("my-react-component");
document.append(domElem);
// Render your React component into the div
renderMyReactComponent(domElem);
}
}
2.) Your React component
// MyReactComponent.jsx
import React from "react";
import ReactDOM from "react-dom";
class MyReactComponent extends React.Component {
render() {
// JSX, woah!
return <h2>My React Component</h2>
}
}
// A way to render your React component into a specific DOM element
export const renderMyReactComponent = (domElem) => {
// NB: This syntax works for React 16.
// React 18 requires a slightly different syntax.
ReactDOM.render(
<MyReactComponent />,
domElem
);
}
3.) A way to parse jsx files and build the app
I use Webpack and amended my existing Webpack configuration based on this article: https://medium.com/#JedaiSaboteur/creating-a-react-app-from-scratch-f3c693b84658 (The official React documentation also points at this tutorial)
Useful Articles
A good read is this article from the official React documentation: https://reactjs.org/docs/add-react-to-a-website.html. This also explains a different way to integrate a React component into your existing JavaScript app using script tags instead of Webpack.
You might also be interested in this answer to a similar question as yours.
As #pinkwaffles pointed out in their answer, the following article helps to understand rendering a React component into a DOM element: https://reactjs.org/docs/rendering-elements.html
PS: Note that at the time of writing this answer, the above articles already use React 18 for their examples, whereas my above example still uses React 16; so the syntax regarding ReactDOM is a little different. But the idea is the same.

React renders unnecessary components

In this simple Create-React-App application , I have a simple, static, Header component. For readability the header is held in a separate component. When using : Dveloper Tools - React - and selecting heighlight updates, I'm surprised to see that the Header component renders each time the destination changes. Of course this happens because the state of the parent, the App component, changes.
It was originally build as a functional component; I tried changing it to a React.pureComponent and React.Component with a 'shouldComponentUpdate' function that returns false but it did not help - the component still gets updated/rendered.
I guess this gets to the 'Virtual Dom' and does not render to the actual dom, but in more complicated apps it is still costly. Any suggestions?
Code
Update
I've forked the original repository to demonstrate the issue. In this example the Header component is build with React.Component and shouldComponentUpdate returns false. Yet the header renders each time the destination changes.
Code
When returning false from the ShouldComponentUpdate method React does not run the render method. I confirmed it by adding a console.log command.
However Chrome’s React extension - heighlight updates - still heiglights the Header. The reason for it might be that Header is a sub-component of the App Component, and since the render method of App runs, the Header is heighlighted.
The simplest solution I can think of is to convert your App component to a simple wrapper component around ControlPanel and presentation. Create a new App component which includes the Header and Footer, along with the wrapper component. Please ensure that the App does not have any state of it's own, to avoid re-renders.
My suggestion is to not worry about it, just keep your render functions as cheap as possible and let React do its work.
If you take care to just pass inn the needed props to any component, keep the components as simple as possible and in a sane structure, and make any expensive calculations outside the simple components (to keep them between state changes), that's all the optimizing I would do.
Currently Header is not a component that can implement shouldComponentUpdate.
Implement Header like this:
import React from 'react'
import '../App.css'
import globeLogo from './globe.svg'
export default class Header extends React.Component{
shouldComponentUpdate(nextProps, nextState) {
//compare props and state if need to and decide whether to render or not
//Other wise just return false;
}
render(){
return (
<div className="App-header">
<img src={globeLogo} className="App-logo" alt="logo" />
<h1>Choose My Next Destination</h1>
</div>
)
}
}
Hope that will resolve your query :)

Call react component from javascript

so i have that big project and everything is on pure javascript like Class.create...prototype and functions that render every component on that page and in render with react.I mean when i type function.createElement("div") somehow it create react div.. and so on and everything is on PURE javascript .. so my question is how can i create file with normal react components and and call that react component from that js file? Thank you
From what I understand from your question is that you need to reuse the react component. For that you need to do two things
Export you react component.You can do it as
module.exports = App;
if your react component is like var App = React.createClass()
Secondly in your other react component where you want to reuse this component you can import it as
import {App} from './path/to/resuable/component';
Now use this component in the render() {} function as <App/>

react vs react DOM confusion

I'm using ES6 babel with react, and now for the newer version react, react DOM is not a part of it anymore. My doubt for below code is that, is it the first line require? since nowhere I need React, but the last line I need ReactDOM.
const React = require('react')
const ReactDOM = require('react-dom')
const App = () => {
return (
<div className='app-container'>
<div className='home-info'>
<h1 className='title'>sVideo</h1>
<input className='search' type='text' placeholder='Search' />
<button className='browse-all'> or Browse All</button>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
React from version 0.14 onwards is split into two parts: React and ReactDOM. You are making use of ReactDOM to render you HTML element. So it definitely makes sense for you to import ReactDOM in your Component. But as far as React is concerned although you are not making use of React directly but it is indirectly being used because whatever you write in your return statement will be transpiled into React.createElement function that will create the actual DOM elements.
Now you can see this if you omit React in your code, you will see an error that
react is not present
and it will give you that React is not recognised in React.createElement. Hope you understood it.
From the docs of ReactDOM:
This package serves as the entry point of the DOM-related rendering paths. It is intended to be paired with the isomorphic React, which will be shipped as react to npm.
So your ReactDOM is specifically for DOM related paths for rendering. This used to come tightly coupled with the React package itself, but the built in DOM in React has become deprecated.
Now, Facebook ships the ReactDOM separately as its own package, so yes, you need to include it in your app if you're planning on rendering any of your React. And you also definitely need React itself — ReactDOM is just the DOM side.
Here's a reddit post that explains the separation from React and ReactDOM.
The React team are working on extracting all DOM-related stuff into a separate library called ReactDOM. 0.14 is the first release in which the libraries are split.
Little fun fact, since they want to support backwards compatibility, they kept React's internal DOM but deter people from using it in a funny way.
They are separated from version 0.14 and for any react project, you need to include both, ReactDOM is laying on React, and React, without ReactDOM could not be rendered to the DOM, so the Answer is a big Yes!
React has the need to separate core react code that has nothing to do with generating a web application (HTML DOM). Particularly react-native, there are a different set of packages that are required for React Native and react-dom is not one of them.
If the react library had never split up that DOM related code, a react-native project would have core react code that would be dead weight and then need to be removed using tree shaking and dead code elimination to remove modules in which you have never imported as part of your app.
Having react split this code up makes a lot of sense.

Categories