How to import React from global variable? - reactjs

I have a special scenario. One web application is built upon React. Another JavaScript utility is on React, but that utility is loaded by script tag. So, the application and the utility is built isolatedly. As a result, both the web application bundle file and utility bundle file have React built inside.
Now, we want to make them share one copy of React. It is preferred to export React as global variable in web application code(e.g. global.React) so that the utility can use it directly.
The code in utility is still like below. Hopefully, webpack can ignore it and import React from global.React.
import React from 'react';
import ReactDOM from 'react-dom';
The question is: how to config webpack to tell the utiltiy not to bundle React?

Tested with some non-React application:
in index.html import React from CDN, this will define global React.
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
somewhere in application doing as below, resolves to React instance:
declare var React;
console.log('React is ', React);
So if your first bundle, registers React globally, you may use it.
Just keep in mind, that it considered as bad practice to import from global like this. It beats whole concept of webpack's modularity. For instance, if your first module, upgrades to some backward incompatible version of React, your second module will break eventually as well.
For small projects, might be ok.

Related

Can I use react in some view of my laravel website

I have a laravel website that is currently live and is using blade template for the views and I am thinking of using react JS in some views.
I want to know if it's possible to use react in some views while still having the blade template rendering some views.
OR do I have to rewrite the whole website in react for this to work.
Ok here's some example code that might help you get started with React:
Write a test react app e.g. test.jsx in your resources/js (or .tsx if you're using typescript). It might look something like:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
const root = document.getElementById('react-root');
if (root) {
ReactDOM.render(
<App />,
root
);
}
Here App is the React component root for the feature you are replacing.
You can add this in your webpack.mix.js file as well to transpile it independently or import it in your app.js (which is easier). However in the later case you are loading this code in all views and if there is another page with an element with id react-root there will be problems.
Your blade will now become:
#extends('layouts.index')
#section('content')
<div id="react-root"></div>
#endsection
Of course here it is oversimplified. You can just replace only the part that has the feature you are transitioning with <div id="react-root"></div> and have react handle that part from then on.
You can also do this multiple times in a single .blade.php file by making multiple calls to ReactDOM.render on different root elements. React will be fully responsible for everything under the root elements it renders to and the rest of your code will continue to run as before. However be aware that code that relied on element selectors via e.g. jQuery should not be used to manipulate nodes that React manages as that may cause problems.

REACT import css and js files

My application needs to have two pages, one landing page and one admin page. Both pages use different themes. I could not integrate css and js files of these two pages in a single page application.
const jquery = require('mdbootstrap/js/jquery-1.11.3.min.js');
window.jQuery = jquery;
window.$ = jquery;
require('mdbootstrap/css/bootstrap.min.css');
require('template/homePage/js/plugins/owl-carousel/owl.carousel.css');
require('template/homePage/js/plugins/owl-carousel/owl.theme.css');
require('template/homePage/js/plugins/owl-carousel/owl.transitions.css');
require('template/homePage/css/animate.css');
require('template/homePage/js/plugins/YouTube_PopUp-master/YouTubePopUp.css');
require('template/homePage/css/preloader.css');
require('template/homePage/css/style.css');
require('mdbootstrap/js/popper.min.js');
require('mdbootstrap/js/bootstrap.min');
require('template/homePage/js/plugins/vivid-icons');
require('template/homePage/js/plugins/owl-carousel/owl.carousel.js');
require('template/homePage/js/plugins/YouTube_PopUp-master/YouTubePopUp.jquery.js');
require('template/homePage/js/plugins/wow/wow.js');
require('template/homePage/js/plugins/jquery.easing.min.js');
require('template/homePage/js/main');
this sample import not good work. And I need outside link css and js.
I have two problem one of them is $(...).scrollspy is not a function
other WOW is not a function.
None of them work in sequence.
When you want to import resources into your React app, you use imports like this:
// Import with variable assignation
import logo from './logo.png';
// Import without variable assignation
import './css/index.css'
You can read more about this in the create-react-app documentation:
https://create-react-app.dev/docs/adding-images-fonts-and-files/
You can read more about ES7 imports here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
I see what you're trying to do is to add libraries and resources to your app component, like if were a common html file, you can't do that in React , you need to find an implementation.
It is not recommended to use jQuery with React, because you use jQuery to write code in a simple and fast way to create complex implementations, now those complex implementations can be made with just React and JS, that is what React is designed for.
Now I understand that you might want to use jQuery even do is not that recommendend, so here is a link where you can get jQuery to install it as a plugin for your React app
https://www.npmjs.com/package/jquery
You would be able to import it to your component like this:
import $ from "jquery";
To use Bootstrap in your React app you check out the documentation of an implementation of Bootstrap for React, react-bootstrap:
https://react-bootstrap.github.io/getting-started/introduction

Setting up webpack to export to set folder

I'm working on an old project still running jquery for frontend, java spring for the backend, and maven for building. I've been asked by my boss to introduce react into the stack so we can toy around with converting some of the pages.
My goal is to not impact the existing implementation to heavily and instead output the result of webpack into a defined directory. This way I can just point the backend at that location for pathing.
So far I have an apps folder in my workspace that contains all my react stuff that works on its own. This was generated using 'npx create-react-app folderName'.
I've somewhat read up on how to set the export but am generally confused. As a lot of resources I've found assume a new setup or a replacement of an existing setup. While I'm looking to only replace a single page currently.
I don't think create-react-app is the right tool here, since you don't create a complete application with React but incrementally add React code. I would suggest using Webpack on its own. This makes your application cleaner and easier to maintain with your other code.
If you want to keep your React code separate from your existing code you can create a library based on webpack's Authoring Libraries Guide. You can than render your components with ReactDOM.render() (Docs). Note that you can call this function (almost) unlimited times on one page which allows you to partially replace your existing code.
Replacing a page then means to create a root DOM element and call the render function:
<!-- page.html -->
<html>
<head></head>
<body>
<!-- more html -->
<div id="page-root" />
<!-- more html -->
</body>
</html>
import React from 'react'
import ReactDOM from 'react-dom'
import Page from './routes/YourPageComponent'
ReactDOM.render(<Page />, document.getElementById('page-root'));
The previous code means that you render your code in the new code which is transpiled by your webpack loaders (e.g. Babel-Loader, Typescript-Loader). If you want to render the code in the existing code, look at the Doc's about Webpack Libraries to export render functions into a global context. The following scripts are an example out of my head.
// components/PageExampleComponent.jsx
import React from 'react';
export default function({pageTitle="example"}){
return <div>
<h1>{pageTitle}</h1>
</div>
}
// libary/index.js
import PageExampleComponent from './components/PageExampleComponent';
export const MyLibrary = {
PageExampleComponent
}
The previous code requires the following (partial) Webpack config to export MyLibrary:
module.exports = {
//...
output: {
library: 'MyLibrary',
// based on a fast look into the docs, I think the following are optional:
libraryTarget: 'window',
libraryExport: 'default'
}
};
To render a component of this library, you need React and ReactDOM as scripts in your website - and of course your own library script. You can than call ReactDOM.render() in plain JavaScript:
ReactDOM.render(
React.createElement(window.MyLibrary.PageExampleComponent),
document.getElementById('page-root')
Another idea would be to move everything into Webpack. This might be easier, as you don't have barriers of different Javascript-Versions and dialects (e.g. with and without JSX support). You can even separate your jQuery code and your React code by using two entry points:
module.exports = {
//...
entry: {
oldCode: './src/jqueryIndex.js',
replacement: './src/reactIndex.js'
},
output: {
filename: "[name].js"
}
};

Separated Apps - but shared react-js-core

I plan to rewrite parts of our Site using React.js (Apps have only our Stylesheets, base HTML structure in common, they use different Data-Sources).
But what I need to know, before I start:
Is it possible to reuse the React Core
import React, { Component } from 'react';
or must each "App" load/compile it's own, -> overhead per App
It's just an importing into the scope of your module, really webpack will import React only once.
If you want to make a few bundles of your app, it will be correct to exclude React (and other libraries) from bundles to prevent loading it many times. For this case webpack provides an option externals.
Webpack docs
Issue about React as externals

React vs ReactDOM?

I'm a bit new to react. I see we have to import two things to get started, React and ReactDOM, can anyone explain the difference. I'm reading through the React documentation, but it doesn't say.
React and ReactDOM were only recently split into two different libraries. Prior to v0.14, all ReactDOM functionality was part of React. This may be a source of confusion, since any slightly dated documentation won't mention the React / ReactDOM distinction.
As the name implies, ReactDOM is the glue between React and the DOM. Often, you will only use it for one single thing: mounting with ReactDOM.render(). Another useful feature of ReactDOM is ReactDOM.findDOMNode() which you can use to gain direct access to a DOM element. (Something you should use sparingly in React apps, but it can be necessary.) If your app is "isomorphic", you would also use ReactDOM.renderToString() in your back-end code.
For everything else, there's React. You use React to define and create your elements, for lifecycle hooks, etc. i.e. the guts of a React application.
The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps. [UPDATE: Upon further research, it's clear my ignorance of React Native is showing. Having the React package common to both web and mobile appears to be more of an aspiration than a reality right now. React Native is at present an entirely different package.]
See the blog post announcing the v0.14 release:
https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html
From the React v0.14 Beta release announcement.
As we look at packages like react-native, react-art, react-canvas, and react-three, it's become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To make this more clear and to make it easier to build more environments that React can render to, we're splitting the main react package into two: react and react-dom.
Fundamentally, the idea of React has nothing to do with browsers, they just happen to be one of many targets for rendering trees of components into. The ReactDOM package has allowed the developers to remove any non-essential code from the React package and move it into a more appropriate repository.
The react package contains React.createElement, React.createClass and React.Component, React.PropTypes, React.Children, and the other helpers related to elements and component classes. We think of these as the isomorphic or universal helpers that you need to build components.
The react-dom package contains ReactDOM.render, ReactDOM.unmountComponentAtNode, and ReactDOM.findDOMNode, and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString and ReactDOMServer.renderToStaticMarkup.
These two paragraphs explain where the core API methods from v0.13 ended up.
TL;TR the react package is required to create and use components and hooks, react-dom contains react-dom/client and react-dom/server to render you app in the browser's DOM or inside a string (or a stream) on the server. With react-native you can use React to create native apps for Android and iOS.
This question has been asked almost seven years ago and a lot has changed since then.
Most of the answer are no longer correct or contains outdated information.
I'll try to give you a complete but simple answer with the most up to date information available.
React 18
In March 2022 React 18 has been released. It has brought some interesting changes in its public APIs.
Packages
react
As stated in React documentation:
React is the entry point to the React library. If you load React from a <script> tag, these top-level APIs are available on the React global.
Indeed it exposes most of the common React features to create and use components. Some of these are:
React.Component and React.PureComponent, used to create class components and function components
React.createElement(), used convert your JSX code from <Page title="Home page" />to React.createElement(Page, { title: "Home page" }, null)
React.Fragment, to return multiple elements without creating additional DOM elements (starting with React 16.2 you can also use <></> to create a fragment.
hooks, to let you use state and other React features without writing a class
Refs, Suspence and Transitions
Complete list of API exposed by the React object
react-dom, react-native and the others listed below are React renderers. They manage how a React tree turns into the underlying platform calls.
react-dom
The react-dom package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.
This package is essentially a container used to expose both the client and server sub-packages from a single one. Indeed it exposes only two function:
createPortal(), used to create portals and render children outside the DOM hierarchy of the parent component
flushSync() is something you may not never have heard about and for a reason. Because it can significantly hurt performance.
Starting from React 18 these functions have been flagged as legacy, so they will be deprecated in future releases:
render()
hydrate()
findDOMNode()
unmountComponentAtNode()
If you are thinking "OMG they have deprecated the ´ReactDOM.render´ method from React", don't worry and read below.
The reason behind the deprecation is:
the opportunity to redesign the APIs we expose for rendering on the client and server. These changes allow users to continue using the old APIs in React 17 mode while they upgrade to the new APIs in React 18.
Keep in mind that if you continue to use those legacy APIs, new React 18 features will be disabled.
Complete list of API exposed by the react-dom package
react-dom/client
The react-dom/client package provides client-specific methods used for initializing an app on the client. Most of your components should not need to use this module.
The React DOM Client module exposes only two methods:
createRoot() is the new method to create a root where your app will. This the replacement for ReactDOM.render - see the example below
hydrateRoot() is the replacement for ReactDOM.hydrate, required to hydrate a server rendered application
Now the idiomatic way to render you app is using createRoot and render chained together:
import React from 'react';
import * as ReactDOM from 'react-dom/client';
ReactDOM
.createRoot(document.getElementById('root'))
.render(<h1>Hello, world!</h1>);
Or using a constant if you don't like chaining, it's just a matter of style:
import React from 'react';
import * as ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<h1>Hello, world!</h1>);
Complete list of API exposed by the react-dom/client package
react-dom/server
The ReactDOMServer object enables you to render components to static markup. Typically, it’s used on a Node server
Using ReactDOMServer you can render React components server-side. It offers a wide range of methods to achieve this - there are dedicated functions for every environment:
renderToPipeableStream(), uses Node.js Streams
renderToNodeStream() (Deprecated), uses Node.js Streams
renderToStaticNodeStream(), uses Node.js Streams
renderToReadableStream(), uses Web Streams available in browsers, Deno, ...
Moreover, there are also render that can be used in the environments that don not support streams:
renderToString() discouraged from React 18
renderToStaticMarkup()
You can use them but they have limited Suspense support.
This is a the minimal working example to try ReactDOMServer on your own:
import React from 'react';
import * as ReactDOMServer from 'react-dom/server';
const html = ReactDOMServer.renderToString(<h1>Hello, world!</h1>);
Complete list of API exposed by the react-dom/server package
react-native
With React Native, React primitives render to native platform UI, meaning your app uses the same native platform APIs other apps do.
React Native has now a huge ecosystem itself and it is not limited to only render components.
Today is no longer recommended to install the react-native module yourself. Instead, you can use the the expo-cli to take advantage of its automation for the development of your application.
Other React renderers
These are some of the most interesting renderer available today (not dead) for React
react-canvas
react-canvas project is dead, but similar features can be found in
react-konva. Using it you can render your React components inside an HTML canvas.
react-three
react-three has been superseded by react-three-fiber. It allows you to build your three.js scene declaratively from React.
ink
ink is a React renderer for CLIs. Using it you can build your CLI output using components.
react-figma
react-figma is a React renderer for Figma. You can use React components as a source for your designs.
react-pdf
react-pdf is a React renderer for creating PDF files on the browser and server.
FAQ
Where did prop-types go?
With the release of react 15.5 the prop-types library
moved outside of React into a dedicated package.
It looks like they've separated React into react and react-dom packages, so you don't have to use the DOM-related part for projects where you'd like to use it in non-DOM-specific cases, like in here https://github.com/Flipboard/react-canvas
where they import
var React = require('react');
var ReactCanvas = require('react-canvas');
as you can see. Without react-dom.
Before v0.14 they were part of main ReactJs file, but as in some cases we may not need both, they separate them and it starts from version 0.14, that way if we need only one of them, our app gonna be smaller due to using only one of those:
var React = require('react'); /* importing react */
var ReactDOM = require('react-dom'); /* importing react-dom */
var MyComponent = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<MyComponent />, node);
React package contains: React.createElement, React.createClass, React.Component, React.PropTypes, React.Children
React-dom package contains: ReactDOM.render, ReactDOM.unmountComponentAtNode, ReactDOM.findDOMNode, and react-dom/server that's including: ReactDOMServer.renderToString and ReactDOMServer.renderToStaticMarkup.
To be more concise, react is for the components and react-dom is for rendering the components in the DOM. 'react-dom' acts as a glue between components and DOM. You will be using render() method of the react-dom to render components in the DOM and that's all you have to know when you are starting off with it.
The ReactDOM module exposes DOM-specific methods, while React has the core tools intended to be shared by React on different platforms (e.g. React Native).
http://facebook.github.io/react/docs/tutorial.html
React: React is a javascript library, designed for building better user interfaces.
React-DOM: React-DOM is a complimentary library to React which glues React to the browser DOM
We’re using React and whenever we use methods like render() or findDOMNode() we’re using React-DOM.
As we look at packages like react-native, react-art, react-canvas, and react-three, it's become clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To make this more clear and to make it easier to build more environments that React can render to, they splitting the main react package into two: react and react-dom.
The react package holds the react source for components, state, props and all the code that is react.
The react-dom package as the name implies is the glue between React and the DOM. Often, you will only use it for one single thing: mounting your application to the index.html file with ReactDOM.render().
Why separate them?
The reason React and ReactDOM were split into two libraries was due to the arrival of React Native (A react platform for mobile development).
The react package holds the react source for components, state, props and all the code that is react.
The react-dom package as the name implies is the glue between React and the DOM. Often, you will only use it for one single thing: mounting your application to the index.html file with ReactDOM.render().

Resources