Module parse failed in npm module - reactjs

I just started learning React and NextJS and I ran into this problem when trying to install a npm package. "Module parse failed: Unexpected token (52:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file". The package I tried installing was React Baraja-JS, https://www.npmjs.com/package/react-baraja-js.
Error message:
error - ./node_modules/react-baraja-js/src/react-baraja.js
Module parse failed: Unexpected token (52:6)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| render() {
| return (
> <ul id={this.props.id} className="baraja-container" ref="wrapper">
| {this.props.children.map((Child, index) => {
| return <li key={index}>{Child}</li>;
cardMenuNav.js
import React from 'react';
import BarajaJS from 'react-baraja-js'; // or '../dist/react-baraja-js';
const cards = [
{
imageSrc: 'path/to/image1.png',
title: 'card 1',
details: 'this is card 1'
},
{
imageSrc: 'path/to/image2.png',
title: 'card 2',
details: 'this is card 2'
},
{
imageSrc: 'path/to/image3.png',
title: 'card 3',
details: 'this is card 3'
},
{
imageSrc: 'path/to/image4.png',
title: 'card 4',
details: 'this is card 4'
},
// add more cards ...
]
export default class Demo extends React.Component {
constructor() {
super();
this.state = {
fan: {}
};
}
// Fan right
fanEvent() {
this.setState({
fan: {
direction: 'right',
easing: 'ease-out',
origin: {
x: 25,
y: 100
},
speed: 500,
range: 90,
center: true
}
});
}
render() {
return (
<React.Fragment>
<button id="fan-button" onClick={() => this.fanEvent()}>Fan right</button>
</React.Fragment>
);
}
};
index.js
import Image from 'next/image'
import CardMenuNav from '../components/cardMenuNav';
const Home = () => {
return (
<div>
<CardMenuNav />
</div>
);
}
export default Home;
package.json
{
"name": "Alcohol-Business-Website",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"antd": "^4.22.8",
"bootstrap": "^5.2.0",
"next": "12.2.5",
"react": "18.2.0",
"react-baraja-js": "^1.0.7",
"react-bootstrap": "^2.5.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"eslint": "8.23.0",
"eslint-config-next": "12.2.5"
}
}
These are the codes that I am working with. I'm not too sure what is wrong but I did some research and it said that I had a duplicate package or something is wrong with my webpack.

Related

Are dynamic and external React components possible in runtime?

We're developing a dashboard React-application in which other (trusted) developers can create their own React-widgets in separate environments. The goal would be a situation where new widgets wouldn't require updation to the dashboard-application and instead, these external React-components could be loaded at runtime.
So developer A would have his own project, where he would bundle a React-component into a js-file, which would be forwarded to a hosting site, S3 for example where the dashboard application could read them via a string, at runtime.
For example a weather-widget:
import React, {useState} from "react";
function Weather() {
const [city, setCity] = useState("city");
const weatherUri = `https://wttr.in/${city}_tqp0.png`;
return (
<div>
<input type="text" value={city} onChange={(e) => setCity(e.target.value)}/>
<div>
<img src={weatherUri} alt={city}/>
</div>
</div>
);
}
export default Weather;
This could be then imported to the dashboard-application. I've understood that React's dynamic code-splitting with dynamic url would work here. Either via a situation where widget would have its own React-library, or it'd get it from the dashboard-application. We've, in fact, made this to work, but as soon as we add a state to the component, it breaks:
Uncaught TypeError: Cannot read properties of null (reading 'useState')
at Object.useState (react.development.js:1612:23)
at Weather (weather_widget.js:36:33)
We've configured the widget-component's configuration as follows (React-library will be imported from the dashboard-application):
// ====== vite.config.js ========== (widget)
export default defineConfig({
plugins: [react()],
define: {
'process.env': {}
},
build: {
lib: {
entry: 'src/lib/Weather.tsx',
name: 'Weather',
fileName: 'weather',
formats: ['es']
},
rollupOptions: {
plugins: [
externalGlobals({
react: "React"
})
],
external: ['react'],
output: {
globals:{
react: 'React'
}
}
}
},
})
// ===== package.json ===== (widget)
{
"name": "weather",
"private": true,
"version": "0.0.0",
"type": "module",
"files": [
"dist"
],
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "18.2.0",
"react-dom": "18.2.0",
"rollup-plugin-external-globals": "^0.6.1"
},
"devDependencies": {
"#types/node": "18.7.23",
"#types/react": "18.0.21",
"#types/react-dom": "^18.0.6",
"#vitejs/plugin-react": "^1.0.7",
"path": "^0.12.7",
"typescript": "^4.6.4",
"vite": "^2.8.0"
}
}
This is how we've tried to import it to the dashboard-application:
export const WidgetCard = (widgetId: string) => {
const WidgetComponent = React.lazy(() =>
import(`/path/to/${widgetId}.js`));
return
<>
<Suspense fallback={<Loading/>}>
<WidgetComponent/>
</Suspense>
</>
)
});
For the final product, the logic would be as follows:
User will generate a JS-bundle of their React-component
User will call some sort of API, which will save bundle to a hosting site and also add the new widget to a database of some sort.

My Uppy suddenly gives me the error this.uppy.addFiles is not a function

I'm new to this and I get this error and can't figure out why please advice:
Looks like the Error is inside Uppy something.
I follow Uppy Tutorial docs like .use(Dashboard, {... and it was working but suddenly this error I try to back track but no luck
I add files from My Device and and then error happens no breakpoint are hit anywhere what I'm a missing
Here is my simple Uppy:
import React from "react";
import "#uppy/core/dist/style.css";
import "#uppy/status-bar/dist/style.css";
import "#uppy/drag-drop/dist/style.css";
import "#uppy/progress-bar/dist/style.css";
import "#uppy/dashboard/dist/style.css";
import "./styles.css";
const Uppy = require("#uppy/core");
// const Dashboard = require("#uppy/dashboard");
const GoogleDrive = require("#uppy/google-drive");
const Dropbox = require("#uppy/dropbox");
const Instagram = require("#uppy/instagram");
const Webcam = require("#uppy/webcam");
const Tus = require("#uppy/tus");
const {
Dashboard,
DashboardModal,
DragDrop,
ProgressBar,
} = require("#uppy/react");
class DashboardUppy extends React.Component {
constructor(props) {
super(props);
this.form = React.createRef();
this.state = {
showInlineDashboard: false,
open: false,
};
this.uppy = new Uppy({
id: "uppy1",
autoProceed: false,
debug: true,
allowMultipleUploads: true,
showSelectedFiles: true,
restrictions: {
maxFileSize: 1000000,
maxNumberOfFiles: 100,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', 'video/*'],
},
onBeforeFileAdded: (currentFile, files) => {
console.log(files);
const modifiedFile = Object.assign({}, currentFile, {
name: currentFile + Date.now(),
});
if (!currentFile.type) {
// log to console
this.uppy.log(`Skipping file because it has no type`);
// show error message to the user
this.uppy.info(`Skipping file because it has no type`, "error", 500);
return false;
}
return modifiedFile;
},
})
.use(Tus, { endpoint: "https://master.tus.io/files/" })
.use(GoogleDrive, { companionUrl: "https://companion.uppy.io" })
.use(Dropbox, {
companionUrl: "https://companion.uppy.io",
})
.use(Instagram, {
companionUrl: "https://companion.uppy.io",
})
.use(Webcam, {
onBeforeSnapshot: () => Promise.resolve(),
countdown: false,
modes: ["video-audio", "video-only", "audio-only", "picture"],
mirror: true,
facingMode: "user",
locale: {
strings: {
// Shown before a picture is taken when the `countdown` option is set.
smile: "Smile!",
// Used as the label for the button that takes a picture.
// This is not visibly rendered but is picked up by screen readers.
takePicture: "Take a picture",
// Used as the label for the button that starts a video recording.
// This is not visibly rendered but is picked up by screen readers.
startRecording: "Begin video recording",
// Used as the label for the button that stops a video recording.
// This is not visibly rendered but is picked up by screen readers.
stopRecording: "Stop video recording",
// Title on the “allow access” screen
allowAccessTitle: "Please allow access to your camera",
// Description on the “allow access” screen
allowAccessDescription:
"In order to take pictures or record video with your camera, please allow camera access for this site.",
},
},
})
.on("file-added", (file) => {
const { setFiles } = props;
setFiles(file);
})
}
componentWillUnmount() {
this.uppy.close();
}
render() {
this.uppy.on("complete", (result) => {
console.log(
"Upload complete! We’ve uploaded these files:",
result.successful
);
});
return (
<div>
<div>
<Dashboard
uppy={this.uppy}
plugins={["GoogleDrive", "Webcam", "Dropbox", "Instagram"]}
metaFields={[
{ id: "name", name: "Name", placeholder: "File name" },
]}
open={this.state.open}
target={document.body}
onRequestClose={() => this.setState({ open: false })}
/>
</div>
</div>
);
}
}
export default DashboardUppy;
And I use it like this nothing special:
import React, { useState } from "react";
import FileList from "./FileList";
import FileForm from "./FileForm";
import DashboardUppy from "./DashboardUppy";
import { Container, Grid } from "#material-ui/core";
const CreateContent = () => {
const [file, setItems] = useState();
const [show, showDashboardUppy] = useState(true);
return (
<Container maxWidth="lg">
{show ? (
<DashboardUppy showDashboardUppy={showDashboardUppy}/>
) : (
<Grid container spacing={3}>
<Grid item lg={4} md={6} xs={12}>
<FileList setItems={setItems} />
</Grid>
<Grid item lg={8} md={6} xs={12}>
<FileForm file={file} />
</Grid>
</Grid>
)}
</Container>
);
};
export default CreateContent;
Here is package.json
{
"name": "react-firestore-crud",
"version": "0.1.0",
"private": true,
"dependencies": {
"#uppy/core": "1.0.2",
"#uppy/dropbox": "latest",
"#uppy/form": "^1.3.23",
"#uppy/google-drive": "1.0.2",
"#uppy/instagram": "1.0.2",
"#uppy/react": "^1.0.2",
"#uppy/status-bar": "latest",
"#uppy/tus": "1.0.2",
"#uppy/webcam": "latest",
"#uppy/xhr-upload": "^1.6.8",
"#material-ui/core": "^4.11.2",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.57",
"#material-ui/styles": "^4.11.2",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"bootstrap": "^4.5.2",
"clsx": "^1.1.1",
"firebase": "^7.23.0",
"moment": "^2.29.1",
"prop-types": "^15.7.2",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-perfect-scrollbar": "^1.5.8",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.0",
"uuid": "^8.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I hade the wrong Uppy version in package.json hmmm

Getting problems implementing react-select package

I am working in a react app that is a form that contains a few dropdown components (from MS fabric).
I got a request asking for change some of these dropdown to combobox and the MS fabric combobox package doesn't work very well so I looked the internet and I found a package called React-select.
I tested the package in a simple react app before implementing it in the real project and it worked very well.
The problem is when I try to implement the same package in the real project. The problem is that as soon I implement the component my app stop working. If I remove the line the app works again.
The major difference between the test app and the real project is that in the project I am using Typescript. I have also other components in the project and just for testing I removed all of them but the problem remain.
No error messages in the developer console nor in the react app itself.
My implementation is like this:
Import the module:
import Select from "react-select";
Inside componentDidUpdate:
componentDidUpdate(prevProps: ISearchPersonFormProps): void {
if (this.props != prevProps) {
let civilServants = [] as any;
this.props.civilServants.forEach(civilServant => {
civilServants.push({ label: civilServant.PKATBESKR, value: civilServant.Id })
})
this.setState(
{
civilServants: civilServants
});
}
In my ISearchPersonFormProps I have this interface:
civilServants: ICivilServant[];
And in the render method i use the like this:
<Select options={this.state.civilServants} />
The civilServants state is of type IDropdownOptions[].
I tested the state of civilServants just before the Select-line and it contains all the information that I want to use in the Select component.
When I remove this Select-line the app works again otherwise nothing shows on the screen and no error message shows in the dev console.
Some info of my app:
React version: 16.11.10
Typescript version: 3.7.2
React-select version: 3.0.8
#types/react-select version: 3.0.8
Any comment will be helpful,
Thanks!
UPDATE:
this is the code for the component:
import * as React from "react";
import {
TextField,
Dropdown,
IDropdownOption,
Checkbox,
PrimaryButton,
Stack,
Label
} from "office-ui-fabric-react";
import { ISearchPersonFormProps } from "./ISearchPersonFormProps";
import { ISearchPersonFormState } from "./ISearchPersonFormState";
import Select from "react-select";
export class SearchPersonForm extends React.Component<
ISearchPersonFormProps,
ISearchPersonFormState
> {
constructor(props: ISearchPersonFormProps) {
super(props);
this.state = {
civilServants: [],
selectedOption: null
};
this._handleChange = this._handleChange.bind(this);
}
componentDidUpdate(prevProps: ISearchPersonFormProps): void {
if (this.props != prevProps) {
let civilServants: any[] = [];
this.props.civilServants.forEach(civilServant => {
civilServants.push({
value: civilServant.Id,
label: civilServant.PKATBESKR
});
});
this.setState({
civilServants: civilServants
});
}
}
private _handleChange = (selectedOption: any) => {
this.setState(
{
selectedOption
},
() => console.log(this.state.selectedOption)
);
};
public render(): React.ReactElement<ISearchPersonFormProps> {
const { selectedOption } = this.state;
console.log(this.state.civilServants);
return (
<div className="search-form">
<Stack horizontalAlign="start" tokens={{ childrenGap: 20 }}>
<Stack horizontal tokens={{ childrenGap: 25 }}>
<Select
value={selectedOption}
onChange={this._handleChange}
options={this.state.civilServants}
/>
</Stack>
</Stack>
</div>
);
}
}
This is the code for the porp interface:
import { ICivilServant } from "./ICivilServant";
export interface ISearchPersonFormProps {
civilServants: ICivilServant[];
}
This is the code for the state interface:
export interface ISearchPersonFormState {
selectedOption: any;
civilServants: any;
}
The ICivilServant is the interface that is used when the data is fetched from the DB.
The console log in the component shows that the data from the DB is correctly fetched.
But as I said before, as soon I add the Select component the app stop working without any error message.
UPDATE 2: Package.json
{
"name": "rk-proper",
"description": "Displays forms and listings (mostly) for everything regarding the solution.",
"configurationType": "Web Part",
"cewpHtmlContent": "<div id=\"proper-webpart-container\">​</div>",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"dev": "concurrently \"webpack --config webpack.dev.js --watch\" \"gulp serve\"",
"build": "webpack --config webpack.release.js",
"build-dev": "webpack --config webpack.dev.js",
"clean": "gulp clean",
"configure-sp": "#powershell -NoProfile -ExecutionPolicy Unrestricted -Command ../StartDevelopment.ps1"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/react": "^16.9.11",
"#types/react-dom": "^16.9.4",
"#types/react-table": "^6.8.5",
"#types/react-tabs": "^2.3.1",
"assets-webpack-plugin": "^3.9.10",
"awesome-typescript-loader": "^5.2.1",
"concurrently": "^5.0.0",
"gulp": "^4.0.2",
"#types/sharepoint": "^2016.1.6",
"gulp-clean": "^0.4.0",
"gulp-serve": "^1.4.0",
"node-sass": "^4.13.0",
"source-map-loader": "^0.2.4",
"typescript": "^3.7.2",
"webpack-cli": "^3.3.10",
"webpack-merge": "^4.2.2",
"office-ui-fabric-react": "^7.54.0",
"react-table": "^6.10.3",
"react-tabs": "^3.0.0"
}
}
Checkout this example here. Instead of value prop they are using defaultValue. Take a look of the documentation and try to change it in your code to see if this is the problem.

Proper way to use botframework-webchat in React component (using create-react-app)?

I've created an app using create-react-app, then used the official github instructions for integrating with React (v16.6.3):
import DirectLine from 'botframework-directlinejs';
import React from 'react';
import ReactWebChat from 'botframework-webchat';
export default class extends React.Component {
constructor(props) {
super(props);
this.directLine = new DirectLine({ token: 'YOUR_BOT_SECRET' });
}
render() {
return (
<ReactWebChat directLine={ this.directLine } />
element
);
}
}
However, I'm getting this error:
TypeError: botframework_directlinejs__WEBPACK_IMPORTED_MODULE_5___default.a is not a constructor
What am I missing here? Thanks!
Note, there is (at time of writing this) an error in the instructions in the official repo:
import DirectLine from 'botframework-directlinejs';
should be:
import { DirectLine } from 'botframework-directlinejs';
Change this, and botframework-webchat v4 works with React 16, with the instructions on the github page.
If you want to use v3 of botframework-webchat, the following code worked for me:
After some experimenting and digging in other repos, here's how I was able to do this using a clean create-react-app instance:
in /src/App.js:
import React, { Component } from 'react';
import * as WebChat from 'botframework-webchat';
class App extends Component {
constructor(props) {
super(props);
this.state = { token: null };
}
async componentDidMount() {
const myHeaders = new Headers()
var myToken = process.env.REACT_APP_DIRECTLINE_SECRET
myHeaders.append('Authorization', 'Bearer ' + myToken)
const res = await fetch(
'https://directline.botframework.com/v3/directline/tokens/generate',
{
method: 'POST',
headers: myHeaders
}
)
const { token } = await res.json()
this.setState(() => ({ token }))
}
render() {
const {
state: { token }
} = this;
return (
!!token &&
<WebChat.Chat
directLine={{
token,
webSocket: false
}}
style={{
height: '100%',
width: '100%'
}}
user={{
id: 'default-user',
name: 'Some User'
}}
/>
);
}
}
export default App;
Add this line before the title tag in /public/index.html:
<link
rel="stylesheet"
href="https://cdn.botframework.com/botframework-webchat/0.14.2/botchat.css"
/>
package.json -- note I'm using the 0.14.2 version of botframework-webchat, I can't get it to work on the master release (4.1.1 as of right now):
{
"name": "react-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"botframework-webchat": "^0.14.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-scripts": "^2.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
And don't forget to set your secret in .env!

How to do the export and import of object (map object) in ReactJS?

I am having RAS_MapComponent class and this will display the openlayers map with some defaulted linestring in the map.
I want to test the defaulted linestring coordinates in another class.So, I need to pass the map Object to my test class from RAS_MapComponent class. I have tried to export the map Object using props and it is throwing an error.
How can I export the map object from the main class (RAS_MapComponent) to test class ()?
I am getting an error in the below line in test class
var maplayers=MapComponent.map.getLayers();
Main Class:
class RAS_MapComponent extends Component {
componentDidMount() {
var raster=new Tile({
source: new OSM()
});
//Location A - Latitude and Longitude
var coords1 = proj.fromLonLat([79.2652587890625,19.532871485421026]);
var iconFeature1 =new Feature({
geometry: new Point(coords1),
name: 'Marker 1' });
//Location B - Latitude and Longitude
var coords2 = proj.fromLonLat([81.24279785156249,18.02679570052561]);
var iconFeature2 =new Feature({
geometry: new Point(coords2),
name: 'Marker 2' });
var lineBetweenTwoFeatures =new Feature({
geometry: new LineString([coords1, coords2]),
name: 'Line between markers',
});
var source = new SourceVector({
features: [iconFeature1,iconFeature2,lineBetweenTwoFeatures],
wrapX: false
});
var width = 3;
var vector = new LayerVector({
source: source,
style: [
new Style({
stroke: new Stroke({
color: 'white',
width: width + 2
})
}),
new Style({
stroke: new Stroke({
color: 'red',
width: width
})
})
]
});
var map = new Map({
target: 'map',
layers: [raster,vector],
view: new View({
center: proj.fromLonLat([78.8718, 21.7679]),
zoom: 4
})
})
map.getView().fit(source.getExtent());
}
render() {
return (
<div id="map" class="map"></div>
)
}
}
export default RAS_MapComponent;
Test Class:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import MapComponent from "./components/RAS_MapComponent";
it('Check the Long and lat from map',()=> {
var maplayers=MapComponent.map.getLayers();
maplayers.forEach(function(layer) {
if(layer instanceof LayerVector){
var features = layer.getSource().getFeatures();
features.forEach(function(feature) {
console.log("Features Coordinates :"+proj.toLonLat(feature.getGeometry().getCoordinates()));
});
}
});
});
Error:
export default _ol_;
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at Object.<anonymous> (src/components/RAS_MapComponent.js:4:11)
at Object.<anonymous> (src/App.test.js:4:25)
Node Version : v8.10.0
Package.JSON:
{
"name": "react_spa",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"chart.js": "^2.7.2",
"d3-chart": "0.0.1",
"ol": "^4.6.5",
"ol-contextmenu": "^3.2.0",
"prop-types": "^15.6.1",
"react": "^16.4.0",
"react-chartjs": "^1.2.0",
"react-chartjs-2": "^2.7.2",
"react-dom": "^16.4.0",
"react-minimal-pie-chart": "^3.0.2",
"react-ol": "^0.1.12",
"react-scripts": "1.1.4",
"recharts": "^1.0.0-beta.10"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"react-openlayers": "^0.2.1"
}
}

Resources