I'm currently trying to use react-pdf to generate and save a pdf to disk. Rendering to a webpage works, but the method that I need to invoke to save a pdf to disc,
ReactPDF.render()
does not work within the npm start (react-scripts) way of running React that I've used in the past to create webpages. From reading this issue, it seems that it needs to be run as a "Node only api". So my question is, what dependencies, commands, and steps do I need to take to run some react code and save a pdf to disk with something like
> node index.js
currently when I run the above command I get
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
Then, running
node --experimental-modules index.mjs
I get
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
^
SyntaxError: Unexpected token <
Here are my two files:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ReactPDF from '#react-pdf/renderer';
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
//ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React, { Component } from 'react';
import { Document, Page, Text, View, StyleSheet } from '#react-pdf/renderer'
class App extends Component {
render() {
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
}
}
export default App;
package.json
{
"name": "ccv-generator-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#react-pdf/renderer": "^1.4.2",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-scripts": "2.1.8",
"ts-pnp": "^1.0.1",
"typescript": "^3.3.4000"
},
"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"
],
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
A follow up question would be, Is what I am trying to do an anti-pattern?
Since you're running index.mjs directly from node, it does not go through the build and transpilation process of react-scripts, meaning you have to do it manually.
Node cannot directly parse jsx (<App/>, for example) - so you will need to run your code through Babel with React preset in order to run it.
Since the dependecies should be already installed, try running:
npx babel index.mjs -o index-compiled.js --presets=es2015,react
and then run the compiled file:
node index-compiled.js
Related
I'm new on React and I'm stuck on something. I added a new component as a 'react-customizable-progressbar' in my project. I have the following files in yellow. These were the ones that I created.
The problem point to
ERROR in ./src/example1.js 6:0-73
Module not found: Error: Can't resolve './CircularProgressBarContainer' in 'C:\Alex Maricoiu\Projects\React projects\project1\src'
Failed to compile.
CircularProgressBarContainer.tsx have the following code:
import React, {FunctionComponent} from "react";
import ICustomIndicatorProperties from './IProgressBarProperties';
import ProgressBar from 'react-customizable-progressbar'
const CustomProgressIndicator : FunctionComponent<ICustomIndicatorProperties> = ({value, title}) => {
return (
<div className="text-and-value" style={{width: "29em"}}>
<div className="title-text">{title}</div>
<div className="custom-progress-bar">
<ProgressBar
radius={100}
progress={value}
strokeWidth={18}
strokeColor="#5d9cec"
strokeLinecap="square"
trackStrokeWidth={18}
>
<div className="indicator">
<div>{value}%</div>
</div>
</ProgressBar>
</div>
</div>
)
};
export default CustomProgressIndicator;
Example1.js:
import {useState} from 'react';
import {CustomProgressIndicator} from './CircularProgressBarContainer';
function Button(props) {
return (
<button onClick={props.onClickFunc}>
Increment by 1
</button>
);
}
function Display(props){
// eslint-disable-next-line no-undef
const [counter, setCounter] = useState(0);
const incrementValue = () => setCounter(counter+1);
return (
<div>
<Button onClickFunc={incrementValue}/>
<b> Current value is: {counter}</b>
<CustomProgressIndicator
value={counter}
title ='Indicator Exercise 1'
/>
</div>
)
}
function App(props){
return (
<div>
<Display />
</div>
)
}
export default App;
The Interface file has (IProgressBarProperties.tsx):
interface ICustomIndicatorProperties {
title: string;
value: number;
}
export default ICustomIndicatorProperties;
And Main.js:
import './Main.css';
import Example1 from './example1';
import { Component } from 'react';
class App extends Component {
render(){
return (
<>
<div className='header'>Alex React Examples</div><div className='content'>
<h3>Example #1</h3>
<div id='example1Node'>
<Example1 />
</div>
</div>
</>
);
}
}
export default App;
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import MainApp from './Main';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<MainApp />
</React.StrictMode>
);
package.json:
{
"name": "project1",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-customizable-progressbar": "^1.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Thank you in advance
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Try replacing import {CustomProgressIndicator} from './CircularProgressBarContainer'; with import CustomProgressIndicator from './CircularProgressBarContainer';, since you are using export default. Curly braces are used for normal (non-default) export. Alternatively remove default from export default.
UPDATE/RESOLVE
I came back with a solution. After I investigate a little seems that there was a incorrect path to the local module created (to the local TSX file).
The UPDATE was in Example1.js. When I put the path, intellisense show me the correct way to import and I hit Enter in order to complete the path. Fine for this. The import looked like this
import {CustomProgressIndicator} from './CircularProgressBarContainer';
The problem was just right here. I correct like it is bellow and it worked.
import {CustomProgressIndicator} from './CircularProgressBarContainer.tsx';
The final result is this. The component marked in yellow was the problem.
Thank you everyone.
I created a new Expo project to play with different animations (npx create-expo-app my-app), and I installed react-native-reanimated and moti (npx expo install react-native-reanimated moti).
When I import it I get no problem, but when I want to do a simple animation I get the following error:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
TypeError: null is not an object (evaluating 'dispatcher.useContext')
Here is my code, which is a simple Loading cicrle:
import * as React from 'react';
import { View } from 'react-native';
//Tried both imports
import { MotiView } from '#motify/components'
import { MotiView } from 'moti'
const LoadingIndicator = ({size}) =>{
return <MotiView
from={{
width:size,
height:size,
borderRadius: size /2,
borderWidth:0,
shadowOpacity:0.5
}}
animate={{
width:size +20,
height:size + 20,
borderRadius: (size +20) /2,
borderWidth:size / 10,
shadowOpacity:1
}}
transition={{
type:'timing',
duration:1000,
// repeat: Infinity,
loop:true
}}
style={{
width:size,
height:size,
borderRadius: size / 2,
borderWidth: size / 10,
borderColor: '#fff',
shadowColor:'#fff',
shadowOffset:{width:0, height:0},
shadowOpacity:1,
shadowRadius:10
}}
/>
}
const LoadingScreen= () => {
return(
<View style={{
flex:1,
alignItems:'center',
// paddingTop:300,
justifyContent:'center',
backgroundColor:'#010100'
}}
>
<LoadingIndicator size={100}/>
</View>
)
}
export default LoadingScreen;
I import this in App.js:
return(
{loading ? <LoadingScreen/> : <MainView/>}
)
And here is my package.json
{
"name": "simple-qrcode",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eas-build-pre-install": "npm install --save --legacy-peer-deps"
},
"dependencies": {
"expo": "~46.0.9",
"expo-dev-client": "~1.2.1",
"expo-status-bar": "~1.4.0",
"moti": "^0.18.0",
"react": "18.0.0",
"react-native": "0.69.5",
"react-native-reanimated": "~2.9.1"
},
"devDependencies": {
"#babel/core": "^7.12.9"
},
"private": true
}
One of the causes of this problem is different versions of React installed. I got the same issue and solved like this.
If you are using npm, run this.
npm install --legacy-peer-deps
Then start the project with expo start -c
If you are using yarn, add this to your package.json and start the project again:
"resolutions": {
"react": "your-version-here"
}
}
you get this error because you have been using a hook outside of a functional component just change it inside and the error will be fixed
Hi I'm having an issue when trying to run my react app. I've installed a couple of packages to from a tutorial using the ceramic and 3id networks. This error has only shown up recently and I've looked online but still not too sure what be causing the issue. The version of node I am using is v14.15.0, my npm version is 6.14.8 and I'm on Windows 11 home version 21H2
The error in question is:
Failed to compile.
./node_modules/did-jwt/lib/index.module.js 1684:17
Module parse failed: Unexpected token (1684:17)
File was processed with these loaders:
* ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| // TODO: should be able to use non base58 keys too
| return key.type === 'X25519KeyAgreementKey2019' && Boolean(key.publicKeyBase58);
> })) ?? [];
| if (!pks.length && !controllerEncrypters.length) throw new Error(`no_suitable_keys: Could not find x25519 key for ${did}`);
| return pks.map(pk => x25519Encrypter(base58ToBytes(pk.publicKeyBase58), pk.id)).concat(...controllerEncrypters);
My package.json file is as follows:
{
"name": "ceramic-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#3id/connect": "^0.2.5",
"#ceramicnetwork/3id-did-resolver": "^1.4.8",
"#ceramicnetwork/http-client": "^1.4.4",
"#ceramicstudio/idx": "^0.12.2",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"dids": "^2.4.0",
"ethers": "^5.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
The current code I have is also just this in my App.js
import './App.css';
import {useState} from 'react';
import CeramicClient from '#ceramicnetwork/http-client'
import ThreeIdResolver from '#ceramicnetwork/3id-did-resolver'
import { EthereumAuthProvider, ThreeIdConnect } from '#3id/connect'
import { DID } from 'dids'
import { IDX } from '#ceramicstudio/idx'
const endpoint = "https://ceramic-clay.3boxlabs.com"
function App() {
const [name, setName] = useState('');
const [image, setImage] = useState('');
const [loaded, setLoaded] = useState(false);
async function connect() {
const addresses = await window.etheruem.request({
method: 'eth_requestAccounts'
})
return addresses;
}
async function readProfile() {
const [address] = await connect();
const ceramic = new CeramicClient(endpoint);
const idx = new IDX({ceramic});
try {
const data = await idx.get(
'basicProfile',
`${address}#eip155:1`
);
console.log('data: ',data);
if (data.name) {
setName(data.name);
}
if (data.avatar) {
setImage(data.avatar);
}
} catch (e) {
console.error('error: ',e);
setLoaded(true);
}
}
return (
<div className="App">
<button onClick={readProfile}>Read Profile</button>
</div>
);
}
export default App;
Update 2021-12-23
This issue is fixed in Create React App version 5.
Create React App does not currently support some features of ES2020 (Modern Javascript) in imported modules.
?? is the ES2020 Nullish coalescing operator and use of this in the imported Ceramic module causes the build to fail.
The issue is discussed here and seems unlikely to be fixed until the next major version of Create React App.
Two options are to use an alternative React framework such as Next.js which supports the features (example/instructions here), or to set up the React project manually.
Other possible solutions are discussed in this stack overflow question, but the accepted answer will not work when the issue occurs in an imported library.
I am new to react native and was trying to create a Onboarding Screen for an app. After adding the code for onboarding screen and importing it into App.js file. I tried to run the application.
However, the app failed to install on my emulator.
The error:
What went wrong:
A problem occurred evaluating project ':react-native-navigation'.
Plugin with id 'kotlin-android' not found.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
2: Task failed with an exception.
What went wrong:
A problem occurred configuring project ':react-native-navigation'.
compileSdkVersion is not specified. Please add it to build.gradle
My build.gradle file looks like this:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "29.0.2"
minSdkVersion = 16
compileSdkVersion = 29
targetSdkVersion = 29
}
repositories {
google()
jcenter()
}
dependencies {
classpath('com.android.tools.build:gradle:4.1.1')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
This is my App.js file
import React, { Component } from 'react';
import SplashScreen from 'react-native-splash-screen';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
//import Screens
import onboardingScreen from './screens/onboardingScreen';
import {
Platform,
StyleSheet,
Text,
View,
StatusBar
} from 'react-native';
const AppStack = createStackNavigator();
export default class App extends Component {
componentDidMount() {
SplashScreen.hide()
}
render() {
return (
<NavigationContainer>
<AppStack.Navigator
headermode="none">
<AppStack.Screen name="onboardingScreen" Component={onboardingScreen} />
</AppStack.Navigator>
</NavigationContainer>
);
}
}
package.json:
{
"name": "Reactnative",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-navigation/native": "^5.8.10",
"#react-navigation/stack": "^5.12.8",
"react": "16.13.1",
"react-native": "0.63.4",
"react-native-app-intro-slider": "^4.0.4",
"react-native-navigation": "^7.6.0",
"react-native-onboarding-swiper": "^1.1.4",
"react-native-splash-screen": "^3.2.0",
"react-navigation-stack": "^2.10.2"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/runtime": "^7.8.4",
"#react-native-community/eslint-config": "^1.1.0",
"babel-jest": "^25.1.0",
"eslint": "^6.5.1",
"jest": "^25.1.0",
"metro-react-native-babel-preset": "^0.59.0",
"react-test-renderer": "16.13.1"
},
"jest": {
"preset": "react-native"
}
}
onboardingScreen.js:
import React from 'react';
import { view, Button, Text, Image, StyleSheet} from 'react-native';
import Onboarding from 'react-native-onboarding-swiper';
const Dots = ({selected}) => {
let backgroundColor;
backgroundColor = selected ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.3)';
return (
<View
style={{
width:6,
height: 6,
marginHorizontal: 3,
backgroundColor
}}
/>
);
}
const Skip = ({...props}) => (
<TouchableOpacity
style={{marginHorizontal:10}}
{...props}
>
<Text style={{fontSize:16}}>Skip</Text>
</TouchableOpacity>
);
const Next = ({...props}) => (
<TouchableOpacity
style={{marginHorizontal:10}}
{...props}
>
<Text style={{fontSize:16}}>Next</Text>
</TouchableOpacity>
);
const Done = ({...props}) => (
<TouchableOpacity
style={{marginHorizontal:10}}
{...props}
>
<Text style={{fontSize:16}}>Done</Text>
</TouchableOpacity>
);
<Onboarding
SkipButtonComponent={Skip}
NextButtonComponent={Next}
DoneButtonComponent={Done}
DotComponent={Dots}
onSkip={() => navigation.replace("Login")}
onDone={() => navigation.navigate("Login")}
pages={[
{
backgroundColor: '#fff',
image: <Image source={require('../assets/img/slider1.png')} />,
title: 'Enabling Collaboration',
subtitle: 'We connect local shoppers to online buyers',
},
{
backgroundColor: '#fff',
image: <Image source={require('../assets/img/slider2.png')} />,
title: 'Peer Up',
subtitle: 'Going home? Ready to help? Drop Orders Get Compensated',
},
{
backgroundColor: '#fff',
image: <Image source={require('../assets/img/slider3.png')} />,
title: 'Enabling Collaboration',
subtitle: 'Busy at home? Need groceries quickly? Want low service fees 0% Mark-up as well? Just make a list',
},
]}
/>
export default onboardingScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
});
I tried googling the error as well, but couldn't find anything related to react-native-onboarding-swiper.
I thought another library produced the error. Try this
android/build.gradle
buildscript {
ext {
minSdkVersion = 21
// kotlinVersion = "1.3.72"
kotlinVersion = "1.6.0"
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" // add this line
}
}
Your App, js import package react-navigation
https://reactnavigation.org/
But, your error shows package resct-native-navigation
https://github.com/wix/react-native-navigation
Be sure about your packages and follow installation guide
Edit:
According to your source code in github
You don't need react-navigation-stack package
You must add some package required
According to doc of react-navigation version 5.x
When you using #react-navigation/stack, you must ensure that you have installed the #react-navigation/native
https://reactnavigation.org/docs/stack-navigator/
Then, when you using #react-navigation/stack, you must install some react-native packages
https://reactnavigation.org/docs/getting-started/#installation
Splash screen freeze because onboardingScreen not found
There are some mistakes when import and export file
So, you can fix it like this:
Number 1 and 2:
package.json
change the package.json, then delete node_modules folder and $ npm install
Number 3:
On screens/onboardingScreen.js you must fix the export
screens/onboardingScreen.js
On App.js you must fix the import
App.js
I'm trying to use this component straight from the Material Ui (Simple Menu https://material-ui.com/demos/menus/#menus) docs in order to make a menu appear. However, I'm getting TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function error with my current attempt below. I tried:
import React, { useState } from 'react'; and then got rid of React inside const [anchorEl, setAnchorEl] = React.useState(null); to make it look like: const [anchorEl, setAnchorEl] = useState(null);
I also tried replacing null with a number but still got same error.
Note: Another attempt installed the right packages and made my package.json file look like this (TypeError dispatcher.useState is not a function when using React Hooks):
{
"name": "speedy-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.9.0",
"#material-ui/icons": "^3.0.2",
"classnames": "^2.2.6",
"node-sass": "^4.11.0",
"prop-types": "^15.6.2",
"react": "16.7.0-alpha.0",
"react-dom": "16.7.0-alpha.0",
"react-test-renderer": "16.7.0-alpha.0",
"react-scripts": "2.1.3"
},
"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"
]
}
Screen shot of error:
What am I doing wrong and how can I fix it?
import React from 'react';
import Button from '#material-ui/core/Button';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
const SimpleMenu = () => {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<Button
aria-owns={anchorEl ? 'simple-menu' : undefined}
aria-haspopup="true"
onClick={handleClick}
>
Open Menu
</Button>
<Menu id="simple-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
};
export default SimpleMenu;
While I'm not sure what is wrong in the code above (my guess is using a non-release build of material-ui in which an export was not default as it documentation states), this error occurred for me with improper imports. My issue was that I was trying to
import someNonDefaultFunction from 'someModule';
Adding the braces around the named/non-default import resolved the same error message for me:
import {someNonDefaultFunction} from 'someModule';