How to solve problem with "Global CSS cannot be imported" in nextjs app? - reactjs

I try to use your library in NextJS app but I accuse following error:
./node_modules/normalize.css/normalize.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: node_modules/react-fullpage-accordion/dist/full-page-accordion.js
I imported all like your example is written
import { FullpageAccordion, Panel } from 'react-fullpage-accordion';
import "react-fullpage-accordion/dist/react-fullpage-accordion.css";
Update.
I renamed react-fullpage-accordion.css to react-fullpage-accordion.module.css, and then try to importem as well.
Error still occur.
./node_modules/normalize.css/normalize.css
Global CSS cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-npm
Location: node_modules/react-fullpage-accordion/dist/full-page-accordion.js
think error is made by this following code
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
require("normalize.css");
var _panelContext = require("./panel-context");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/* eslint-disable react/forbid-prop-types, no-unused-vars, import/no-unresolved, import/extensions */
var FullpageAccordion = function FullpageAccordion(_ref) {
var children = _ref.children,
height = _ref.height;
return /*#__PURE__*/_react["default"].createElement(_panelContext.PanelContextProvider, null, /*#__PURE__*/_react["default"].createElement("div", {
className: "panels",
"data-testid": "panels",
style: {
height: height || '100vh'
}
}, children));
};
FullpageAccordion.defaultProps = {
height: undefined
};
FullpageAccordion.propTypes = {
children: _propTypes["default"].node.isRequired,
height: _propTypes["default"].string
};
var _default = FullpageAccordion;
exports["default"] = _default;
but I am afraid of changing something in third part code.

Related

Unable to unmount React Component

I am trying to unmounted the react component when there is an entity change, for that I am using rerenderSearchPanel function in my angularJS project and then trying to mount it with initializeSearchPanel function.
Inside rerenderSearchPanel I have following code
searchElement && ReactDOM.unmountComponentAtNode(searchElement);
but after executing this line still the component exist its structure.
function rerenderSearchPanel(selectedEntity, savedChips) {
var searchElement = document.getElementById("searchPanel");
searchElement && ReactDOM.unmountComponentAtNode(searchElement);
$scope.initializeSearchPanel(selectedEntity, savedChips);
}
$scope.initializeSearchPanel = function (selectedEntity, savedChips) {
var searchElement = document.getElementById("searchPanel");
var searchDataSource = {
method: "GET",
catalogAPI: $scope.metaRestUrl + "specifications?
q=specName;EQUALS;EntityAttribute&q=subType;EQUALS;English",
searchAPI: $rootScope.smRestUrl + "graphSearch?limit=100&page=1",
selectedEntity: (selectedEntity ? selectedEntity :
$scope.currentEntity),
};
requestConfig.headers['TransformationEnabled'] = true;
searchDataSource.headers = requestConfig.headers
var options = {
searchProps: {
id: "searchInput1",
placeHolder: "Search",
editable: true,
},
chips: savedChips,
onTokenChange: $scope.search,
dataSource: searchDataSource
}
var search = React.createElement(SearchComponent, options);
searchElement && ReactDOM.render(search, searchElement);
}
But ReactDOM.unmountComponentAtNode is not unmounting.

React Native packager isn't including a 3rd party library in the bundle

What's the best way to debug the react-native packager not including a dependency in the output bundle? What I have:
Module is included in package.json and appears in my node_modules
I'm using typescript, and the compiled js file has the require('countdown') line.
If I inspect the output bundle, or log the var countdown = require('countdown'), I can see that the source for countdown.js isn't included in the bundle.
If I use webpack to create a web bundle, it works as expected.
Here's the compiled js code which is having issues:
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var RX = require("reactxp");
var countdown = require("countdown");
var styles = {
outerContainer: RX.Styles.createViewStyle({
flexDirection: "row"
}),
innerContainer: RX.Styles.createViewStyle({
flexDirection: "column",
alignItems: "center",
paddingHorizontal: 5
})
};
var CountdownTimer = (function (_super) {
__extends(CountdownTimer, _super);
function CountdownTimer() {
var _this = _super.call(this) || this;
_this._setStateToNow = function () {
_this.setState({ currentDate: new Date(Date.now()) });
};
_this.state = { currentDate: new Date() };
return _this;
}
CountdownTimer.prototype.componentDidMount = function () {
this.timerId = setInterval(this._setStateToNow, 1000);
};
CountdownTimer.prototype.componentWillUnmount = function () {
clearInterval(this.timerId);
};
CountdownTimer.prototype.render = function () {
// THIS LINE FAILS SINCE 'countdown' is {}
var diff = countdown(this.state.currentDate, this.props.untilDate, CountdownTimer.DIFF_ARGS);
....
};
CountdownTimer.DIFF_ARGS = countdown.DAYS |
countdown.HOURS |
countdown.MINUTES |
countdown.SECONDS;
return CountdownTimer;
}(RX.Component));
exports.CountdownTimer = CountdownTimer;
The error I'm getting is Object is not a function, and logging the var countdown shows it is {}, and inspecting the index.android.bundle shows that the source code for countdown.js isn't included.
I am running the packager with node ./node_modules/react-native/local-cli/cli.js start

React - need for { } to call JS

In the following code (it's a button that changes the color when you click), I don't understand why I need curly braces {} on line9 and 14 but not on line13.
On line 13, we affect state colorGreen to the state color and curly braces are required to read colorYellow variable so we use JS. Am I correct ?
On line 14 it is the same.
On line 13, it is the same, we use colorGreen and color Yellow variable but we don't need curly brace ? Why ?
Thank you
var React = require('react');
var ReactDOM = require('react-dom');
var colorGreen = '#39D1B0';
var colorYellow = '#FFD710';
var Switch = React.createClass({
getInitialState: function () {
return { color: colorGreen }; //line9
},
changeColor: function () {
var changeColor = this.state.color == colorGreen ? colorYellow : colorGreen; //line13
this.setState({ color: changeColor }); //line14
}
});
They're just plain object literals of JavaScript, not any special syntax of React.
You can create an object in JavaScript by:
var obj = {
foo: 'bar'
}
and in your code:
return {
color: colorGreen
}
means create an object and return it immediately.
Please see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

Duplicate constructor in same class in JSX webpack build

I'm having an issue with some code I wrote that's utterly stumped me.
The main JSX tutorial available at the JSX Github Page has an example class called Point, which looks like:
class Point {
var x = 0;
var y = 0;
function constructor() {
}
function constructor(x : number, y : number) {
this.set(x, y);
}
function constructor(other : Point) {
this.set(other);
}
function set(x : number, y : number) : void {
this.x = x;
this.y = y;
}
function set(other : Point) : void {
this.set(other.x, other.y);
}
}
That class has a clear example of a multiple constructor types which I'm familiar from my C++ days. It even has a defined copy constructor, which I think is great.
However, if I got and create a similar class for use by me:
export default class MutableDataStore {
constructor() {
this.data = [];
this.settings = {};
}
//Copy constructor
constructor(other : MutableDataStore) {
this.data = other.data.slice();
this.settings = Object.assign({}, this.settings);
}
//...Other functions omitted
}
I get the following error in my webpack build:
ERROR in ./src/stores/helper-classes/mutabledatastore.jsx
Module build failed: SyntaxError: Duplicate constructor in the same class (8:1)
I'm completely stumped by this, since I can't find anything similar on the web about this, unless it seems to be a transient issue.
My webpack.config.js is:
var webpack = require("webpack");
var path = require("path");
var src = path.resolve(__dirname, "src");
var app = path.resolve(__dirname, "app");
var config = {
entry: src + "/index.jsx",
output: {
path: app,
filename: "javascript.js"
},
module: {
loaders: [{
include: src,
loader: "babel-loader"
}]
}
};
module.exports = config;
and my babel presets are es2015 and react.
Any help would be appreciated!
As loganfsmyth said in the comments, there can only be one constructor in an ES6 class. You can get the desired effect by either checking if other is set in the construct or by providing a default value for the parameter
export default class MutableDataStore {
constructor(other : MutableDataStore) {
this.data = other ? other.data.slice() : [];
this.settings = other ? Object.assign({}, other.settings) : {};
}
//...Other functions omitted
}
// or
export default class MutableDataStore {
constructor(other : MutableDataStore = { data: [], settings: {} }) {
this.data = other.data.slice();
this.settings = Object.assign({}, other.settings);
}
//...Other functions omitted
}
As a side not, I think you might have intended the copy constructor to copy the settings from other, not this.

Loading content dynamically (panels) in an Ext Js Viewport

Well basically im looking on this problem, i have many components with dinamic stuff that is written in the server side with PHP.
Depending on the user my components will change, based on the role of the user.
So i need to know any ways/examples/info on how to do this.
1- I used the load function EXTJS has, but it clearly says i wont load script only plain text.
2- i used eval() but im a bit scared o this approach, like this example crate layout component (static)
var contentPanel = new Ext.Panel({
frame: true,
style: {marginTop: '10px'},
height: 315,
border: true,
bodyBorder: false,
layout: 'fit',
id: 'contentPanel'
});
var mainPanel = new Ext.Panel({
title: 'Panel Principal',
id: 'mainPanel',
border: true,
frame: true,
width: '50%',
style: {margin: '50px auto 0 auto'},
height: 400,
renderTo: Ext.getBody(),
items: [
{
html: 'Panel 1'
},
{
html: 'Panel 2'
},
contentPanel
]
})
and update the content of the layout with js files written on the server
function receiveContent(options, success, response)
{
var respuesta = response.responseText;
//console.log(respuesta);
eval(respuesta);
//console.log(options.url);
url = options.url;
url = url.substring(0,(url.search(/(\.)/)));
var contenedor = Ext.getCmp('contentPanel');
contenedor.removeAll();
var contenido = Ext.getCmp(url);
contenedor.add(contenido);
contenedor.doLayout();
}
function requestContent(panel)
{
//panel es el nombre del archivo que quiero
Ext.Ajax.request({
url: panel+'.js',
callback: receiveContent
});
}
any other way for this to be done, what i DONT want to do is making a million different components and load them ALL at login time like many people seem to say
To address your questions:
The .load method WILL load script and evaluate it once the content has finished loading, however to accomplish this you will need to set the scripts:true option, an example may be:
my_panel.load({
url: 'url_to_load.php/hmt/html/asp...',
params: {param1: param1value, param2: param2value...etc},
nocache: true,
timeout: 30,
scripts: true
});
Using eval() is fine...but seeing as the scripts:true config option above accomplishes this for javascript in the source file, you shouldnt need to use this.
Hope this helps
You might load JavaScript dynamically using something like like below - there are a hundred variations on the web. In this way, you would avoid the AJAX call and handling the response (and subsequent eval).
var aHeadNode = document.getElementById('head')[0];
var aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "someFile.js";
aHeadNode.appendChild(oScript);
What I understood from your question is that, you are looking for dynamic JS file loader with a callback handler i.e. the callback function will be called only when the file is loaded fully. I also faced similar problems at start and after searching a lot and doing some research, I developed the following code, it provides absolute Dynamic JS and CSS file loading functionality :
Class ScriptLoader: (Put it in a separate file and load it at first)
ScriptLoader = function() {
this.timeout = 30;
this.scripts = [];
this.disableCaching = false;
};
ScriptLoader.prototype = {
processSuccess : function(response) {
this.scripts[response.argument.url] = true;
window.execScript ? window.execScript(response.responseText) : window
.eval(response.responseText);
if (response.argument.options.scripts.length == 0) {
}
if (typeof response.argument.callback == 'function') {
response.argument.callback.call(response.argument.scope);
}
},
processFailure : function(response) {
Ext.MessageBox.show({
title : 'Application Error',
msg : 'Script library could not be loaded.',
closable : false,
icon : Ext.MessageBox.ERROR,
minWidth : 200
});
setTimeout(function() {
Ext.MessageBox.hide();
}, 3000);
},
load : function(url, callback) {
var cfg, callerScope;
if (typeof url == 'object') { // must be config object
cfg = url;
url = cfg.url;
callback = callback || cfg.callback;
callerScope = cfg.scope;
if (typeof cfg.timeout != 'undefined') {
this.timeout = cfg.timeout;
}
if (typeof cfg.disableCaching != 'undefined') {
this.disableCaching = cfg.disableCaching;
}
}
if (this.scripts[url]) {
if (typeof callback == 'function') {
callback.call(callerScope || window);
}
return null;
}
Ext.Ajax.request({
url : url,
success : this.processSuccess,
failure : this.processFailure,
scope : this,
timeout : (this.timeout * 1000),
disableCaching : this.disableCaching,
argument : {
'url' : url,
'scope' : callerScope || window,
'callback' : callback,
'options' : cfg
}
});
}
};
ScriptLoaderMgr = function() {
this.loader = new ScriptLoader();
this.load = function(o) {
if (!Ext.isArray(o.scripts)) {
o.scripts = [o.scripts];
}
o.url = o.scripts.shift();
if (o.scripts.length == 0) {
this.loader.load(o);
} else {
o.scope = this;
this.loader.load(o, function() {
this.load(o);
});
}
};
this.loadCss = function(scripts) {
var id = '';
var file;
if (!Ext.isArray(scripts)) {
scripts = [scripts];
}
for (var i = 0; i < scripts.length; i++) {
file = scripts[i];
id = '' + Math.floor(Math.random() * 100);
Ext.util.CSS.createStyleSheet('', id);
Ext.util.CSS.swapStyleSheet(id, file);
}
};
this.addAsScript = function(o) {
var count = 0;
var script;
var files = o.scripts;
if (!Ext.isArray(files)) {
files = [files];
}
var head = document.getElementsByTagName('head')[0];
Ext.each(files, function(file) {
script = document.createElement('script');
script.type = 'text/javascript';
if (Ext.isFunction(o.callback)) {
script.onload = function() {
count++;
if (count == files.length) {
o.callback.call();
}
}
}
script.src = file;
head.appendChild(script);
});
}
};
ScriptMgr = new ScriptLoaderMgr();
Now it can be used this way:
For CSS files loading :
ScriptMgr.loadCss([first.css', 'second.css']);
That is you just need to provide css files path in an array and pass that array to loadCss() function as an argument. No callback is required for CSS files.
For JS file loading :
ScriptMgr.load({
scripts : ['lib/jquery-1.4.2.min.js','lib/jquery.touch-gallery-1.0.0.min.js'],
callback : function() {
//Here you will do those staff needed after the files get loaded
},
scope : this
});
In this case, the same way you entered CSS files, here you just need to put that array of JS files in scripts option. The callback function is called only when all the JS files are loaded successfully. Also, if in any case, the JS files are already loaded in the browser (i.e. already this code is run once), then the control will automatically go to the callback function.

Resources