Destructuring My MUI Text Field Causes It To Break - javascript

Goal: Destructure repetitive components and pass in props to one component for more clear code.
Issue: When copying my MUI TextField component exactly, and then passing it back into the main return, it breaks the component. Whilst typing was slow with formik validation on localhost, it now escapes the TextField upon typing, and only permits one character at a time before requiring the user to click back into the TextField.
Code:
const SimpleTextField = () => {
return (
<TextField
disabled={vacancyStatus === "Expired"}
label="Insurance 2"
variant="outlined"
name={"insurance"}
datacy={"insurance"}
fullWidth
value={formik.values.insurance}
onChange={formik.handleChange}
error={formik.touched.insurance && Boolean(formik.errors.insurance)}
helperText={formik.touched.insurance && formik.errors.insurance}
/>
)
}
Note: All I did was copy the TextField component, add it to SimpleTextField, and then put <SimpleTextField /> back into the main return. The TextField component works when not destructured.
Package.json (shortened)
"dependencies": {
"#emotion/cache": "^11.7.1",
"#emotion/react": "^11.7.1",
"#emotion/server": "^11.4.0",
"#emotion/styled": "^11.6.0",
"#mui/icons-material": "^5.2.4",
"#mui/material": "^5.2.4",
"#mui/x-date-pickers": "^5.0.0-alpha.2",
"card-validator": "^8.1.1",
"dotenv": "^16.0.1",
"express-jwt": "^7.7.5",
"formik": "^2.2.6",
"next": "12.1.5",
"prop-types": "^15.7.2",
"react": "^17.0.2",
"react-countup": "^6.1.0",
"react-dom": "^17.0.2",
"react-slick": "^0.28.1",
"react-syntax-highlighter": "^15.4.5",
"react-visibility-sensor": "^5.1.1",
"yup": "^0.32.11"
},

Related

Component cannot be used as a JSX component in React

The build is normal in other environments, but the following error occurs in my environment.
src/components/popup/CellInfoPopup.tsx:61:24 - error TS2786: 'NumberFormat' cannot be used as a JSX component.
Its instance type 'NumberFormat<unknown>' is not a valid JSX element.
61 <dd><NumberFormat value={meta.price} prefix="₩" thousandSeparator={true} displayType="text"/></dd>
~~~~~~~~~~~~
src/components/popup/InvitationPopup.tsx:49:20 - error TS2786: 'CopyToClipboard' cannot be used as a JSX component.
Its instance type 'CopyToClipboard' is not a valid JSX element.
The types returned by 'render()' are incompatible between these types.
Type 'React.ReactNode' is not assignable to type 'import("/Users/ksh/node_modules/#types/react/index").ReactNode'.
49 <CopyToClipboard
~~~~~~~~~~~~~~~
My settings.
OS : (ARM)MacOS Ventura 13.1
TypeScript : 4.9.4
Node : v18.13.0
npm : 8.19.3
yarn : 1.22.19
My package.json
{
"name": "my-web-service",
"version": "2.8.2",
"scripts": {
"dev": "vite",
"build": "tsc && vite build"
},
"dependencies": {
"#emotion/react": "^11.8.2",
"#react-oauth/google": "^0.5.1",
"#types/lodash": "^4.14.178",
"#types/navermaps": "^3.0.13",
"#types/uuid": "^9.0.0",
"axios": "^0.24.0",
"dayjs": "^1.10.7",
"ga-gtag": "^1.1.1",
"lodash": "^4.17.21",
"next": "12.1.6",
"qs": "^6.10.2",
"rc-pagination": "^3.1.14",
"react": "^17.0.2",
"react-copy-to-clipboard": "^5.0.4",
"react-dom": "^17.0.2",
"react-lottie-player": "^1.4.1",
"react-naver-maps": "^0.0.11",
"react-number-format": "^4.9.1",
"react-popup-manager": "^2.1.3",
"react-query": "^3.34.0",
"usehooks-ts": "^2.9.1",
"uuid": "^9.0.0",
"vite-plugin-html": "^3.0.6",
"wouter": "^2.8.0-alpha.2",
"zustand": "^3.6.7"
},
"devDependencies": {
"#emotion/babel-plugin": "^11.7.2",
"#types/node": "^18.11.18",
"#types/qs": "^6.9.7",
"#types/react": "^17.0.33",
"#types/react-copy-to-clipboard": "^5.0.2",
"#types/react-dom": "^17.0.10",
"#types/uuid": "^9.0.0",
"#vitejs/plugin-react": "^1.0.7",
"typescript": "^4.4.4",
"vite": "^2.7.0"
}
}
Even if Node, Npm, and yarn are all reinstalled, the same error occurs.
Which part is the problem?
React components needs to return a single root element, I have a hunch your NumberFormat & CopyToClipboard components have a malformed return statement.
Ensure your components are not mapping elements like this
function NumberFormat({ items }): JSX.Element {
return items.map(item => (
<>
<li>{item.text}</li>
</>
)
}
but rather return a single element, like so:
function NumberFormat({ items }): JSX.Element {
return <>{
items.map(item => <li>{item.text}</li>)
}</>
}
this error is usually caused by one of these 2 factors :
Your component is an array of jsx elements instead of one element
Returning a value other than a jsx element or null.
if it's not one of these two, and I believe it's not, because you said the build is normal in other environments then try to update your react typings :
npm :
npm install --save-dev #types/react#latest #types/react-dom#latest`
yarn :
yarn add #types/react#latest #types/react-dom#latest --dev
If you also want to update react and react-dom :
npm :
npm install react#latest react-dom#latest
yarn :
yarn add react#latest react-dom#latest
If the problem still occurs then try to delete node_modules and package-lock.json and run npm install

How to properly type component props in react-router?

I have a route
<Route path="/server_form" exact={true} render={(props) => <ServerForm {...props} />}/>
And in the code I have a server which I want to pass when I click a button to my ServerForm
let server = { url: "http://localhost", description: "" }
onClick = {() => {
history.push({
pathname: "/server_form",
state: { ...server },
})
}}
I tried typing props with RouteComponentProps from react-router, but no luck:
type Server = {
url: string;
description: string;
}
interface ServerFormProps extends RouteComponentProps<Server> {
}
export function ServerForm(props: ServerFormProps) {
console.log(props.location.state!.url);
}
On the line with console.log I get the following error:
Property 'url' does not exist on type '{}'. TS2339
How can I properly type it?
P.S. My dependencies
{
"#types/react": "^16.9.49",
"#types/react-dom": "^16.9.8",
"#types/react-router-dom": "^5.1.5",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"typescript": "^4.0.2",
}
Fixed by using new API:
let location = useLocation<Server>()

Hooks can only be called inside of the body of a function component. useState is not working

I have a GatsbyJS project and I am trying to use a Hook, however I am getting this error.
First thing I did was delete the node_modules folder and the package.json.lock file and did npm install again, did not work.
Looking at the React documentation:-
You might have mismatching versions of React and React DOM.
As far as I know I do not have mismatching versions.
You might be breaking the Rules of Hooks. - As far as I am aware I am using a component
You might have more than one copy of React in the same app.
I tried as the React documentation suggests:-
// Add this in node_modules/react-dom/index.js
window.React1 = require('react');
// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2);
This returns false for me so I might have two React however I cannot understand how.
This is my package.json file
{
"name": "gatsby-starter-hello-world",
"private": true,
"description": "A simplified bare-bones starter for Gatsby",
"version": "0.1.0",
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,json,md}\"",
"start": "npm run develop",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
},
"dependencies": {
"gatsby": "^2.21.0",
"gatsby-image": "^2.4.0",
"gatsby-plugin-prefetch-google-fonts": "^1.4.3",
"gatsby-plugin-react-helmet": "^3.3.1",
"gatsby-plugin-sharp": "^2.6.0",
"gatsby-plugin-sitemap": "^2.4.2",
"gatsby-source-filesystem": "^2.3.0",
"gatsby-source-strapi": "0.0.12",
"gatsby-transformer-sharp": "^2.5.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-helmet": "^6.0.0",
"react-icons": "^3.10.0",
"react-markdown": "^4.3.1"
},
"devDependencies": {
"prettier": "2.0.5"
},
"repository": {
"type": "git",
"url": "https://github.com/gatsbyjs/gatsby-starter-hello-world"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
}
}
My component looks like this (just want to verify that the useState works):-
import React, {useState} from "react"
import { graphql, useStaticQuery } from "gatsby"
const query = graphql`
{
allStrapiExperiences(sort: {fields: sequence, order: DESC}) {
nodes {
company
job_title
short_desc
website
address
desc {
id
name
}
job_date
sequence
snapshot {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`
const Experiences = () => {
const data = useStaticQuery(query);
const { allStrapiExperiences: {nodes : experiences} } = data;
const [value, setValue] = useState(0)
// const { company, jobt_title, short_desc, website, address, desc, job_date, sequence, snapshot } = experiences[value]
return (
<div>Some details go here</div>
)
}
export default Experiences
And I am calling this component in the experience.js page:-
import React from "react"
import Experiences from "../components/Experiences/Experiences"
import Layout from "../components/Generic/Layout"
export default () => {
return (
<Layout>
<Experiences />
</Layout>
)
}
I have looked at some posts online, and did some troubleshooting but so far I cannot understand why I am having this problem.
Any ideas why I might be getting this error?
Thanks for your help and time
UPDATE
Just a small update on this, I could not solve the issue, so i took the unwanted route but I thing the best one at the moment to start with the basic blog starter project and start building up from that. Infact, the hooks do work in this project, so I guess I have some mess with dependencies but I cannot figure out what is wrong.
This might seem weird, but can you move your query definition into the call to useStaticQuery? Gatsby uses static analysis to extract these and historically there have been some issues defining a query and assigning it to a variable in this way. For example:
const Experiences = () => {
const data = useStaticQuery(graphql`
{
allStrapiExperiences(sort: {fields: sequence, order: DESC}) {
...
}
}
`);
}
To ensure you don't have multiple versions of React being used, you can try this:
exports.onCreateWebpackConfig = ({ stage, actions }) => {
actions.setWebpackConfig({
resolve: {
// Ensure all dependencies use the same instance of React
alias: { react: path.resolve("./node_modules/react") },
},
})
}

Vuejs v-for error remove element firebase

<tr v-for="(unfilm) in film" v-bind:key="unfilm.key">
<td>
<div id="titolo">{{unfilm.titolo}}</div>
</td>
<td>
<img :src="unfilm.locandina" style="max-width: 50px;">
</td>
<i #click="cancellaFilm(unfilm)" class="material-icons deep-orange-text text-darken-4"
style="cursor: pointer;">delete</i></td>
cancellaFilm(unfilm) {
gamesRef.child(unfilm['.key']).remove()
this.$toastr.info('Errore', 'Attenzione');
// this.$alert("Film cancellato")
}
}
When i clicked button "cancellaFilm" , returned error like:
[Vue warn]: Error in v-on handler: "Error: Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]""
In Cdn mode it works in mpm mode it does not work. I tried to test the problem seems to be due to the macacato passage of the "unfilm" object
What should I modify?
below list the versions of the used packages:
"bootstrap-vue": "^2.13.0",
"core-js": "^3.6.4",
"firebase": "^7.14.2",
"jquery": "^3.4.1",
"ngx-toastr": "^12.0.1",
"popper.js": "^1.16.1",
"toastr": "^2.1.4",
"vue": "^2.6.11",
"vue-simple-alert": "^1.1.1",
"vue-toastr-2": "0.0.10",
"vuefire": "^2.2.2"
In your cancellaFilm() function, unfilm['.key'] is undefined.
Do
gamesRef.child(unfilm['key']).remove()
instead.
I insert the remaining data code:
import {gamesRef} from './firebase'
export default {
firebase: {
film: gamesRef,
}
In firebase.js
import Firebase from 'firebase/app'
import 'firebase/database'
const app = Firebase.initializeApp({
//configuration data
})
export var db = app.database();
export var gamesRef = db.ref('altro')
add_film() {
gamesRef.push(this.nuovoFilm);
}
Is the problem due to the vu js version or the firebase version? What should I change? can you make an example or fix the code?
Thanks a lot

React-native app is being restarted on every navigation when integrated with native app

We're trying to integrate a new React Native app to an existing native Android app. Following the RN official docs we managed to get it working but with some issues regarding the navigation.
We've native and non-native (JS) screens, and we need a good way to navigate between all screens regardless if a screen is native or not.
We tried to adopt native-navigation and react-native-navigation to see if any address our issue but none of them actually worked.
Currently, we have registered all our RN screens like this:
const provide = (store, Screen) => {
return props => (
<Provider store={store}>
<Screen {...props} />
</Provider>
);
};
const store = configureStore();
AppRegistry.registerComponent('Home', () => provide(store, HomeComponent));
We also created a Native Module we call "Navigator" that has navigation method called openComponent that accepts screen name and its props. Here is how the implementation of openComponent looks:
// our native module code ...
#ReactMethod
public void openComponent(String name, String extra) {
try {
Intent intent = new Intent(this.getReactApplicationContext(), MyReactActivity.class);
intent.putExtra("moduleName", name);
intent.putExtra("extra", extra);
getCurrentActivity().startActivityForResult(intent, 0);
}
catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e.getCause());
}
}
Then whenever we want to navigate on the RN side we simply call our custom navigator with the target screen props.
The problem with the current approach is that the RN part is being restarted whenever we navigate to RN-based screens which causes the Redux store to be empty.
Here how our "onCreate" method looks like for our ReactActivity.java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle initialProperties = new Bundle();
initialProperties.putString("loginToken", HJSession.getSession().getSessionId());
initialProperties.putString("username", HJSession.getSession().getUserName());
initialProperties.putString("userId", HJSession.getSession().getUserId().toString());
String moduleName = "topics";
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
moduleName = bundle.getString("moduleName");
try {
String extra = bundle.getString("extra");
initialProperties.putString("extra", extra);
}
catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e.getCause());
}
}
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setJSMainModulePath("index")
.addPackages(Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),
new RNFirebaseMessagingPackage(),
new RNFirebaseNotificationsPackage(),
new RNI18nPackage(),
new VectorIconsPackage(),
new HJRNPackages(),
new NativeNavigationPackage()
))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, moduleName, initialProperties);
setContentView(mReactRootView);
}
Actually, for your question case, you should upload a little tiny scale of your project that has this issue on Gitlab or Github and put its link here, Hence we could help better.
Indeed, I'm a JavaScript, React, React Native developer and I cannot help anybody in the native side, But definitely, I believe you and your colleagues choose the wrong way for your application.
React Native is an unstable JavaScript project that has unstable native codes that are changing in time, so you should write all of your features just by using JavaScript. Just like Sophie Albert said in this article, They wanna make a big break change to React Native, So, It is better all of the codes to be written in JavaScript not native (Java, Objective C).
At first, I believe your choosing on react-native-navigation was wrong. Why you do not use react-navigation?
Because 99.7% of react-navigation based on JavaScript and changing native sides by Facebook teams, do not affect your project and development and debugging is very easy. absolutely, you can use every trend library like Redux, because of your project based on JavaScript.
My colleagues and I are developing a large scale React Native application for Sheypoor, except the splash screen all of the app based on JavaScript and in our inputs tests we didn't get even one crash or error or unwanted restart.
If it is possible for you, roll back your navigation to a full JavaScript navigation library like react-navigation which we chose. If you uploaded a reproduction repository I could help you better than this situation. but I put some of our code structure to help you for roll back to react-navigation:
The index.js of our project:
import { AppRegistry } from 'react-native';
import App from './app/App';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);
The root file of our app, the App.js file:
import React from 'react';
import { Provider } from 'react-redux';
import RootNavigation from './RootNavigation';
import { onNavigationStateChange } from './utils/routes';
import configureStore from './redux/configureStore';
const store = configureStore();
const App = () => (
<Provider store={store}>
<RootNavigation onNavigationStateChange={onNavigationStateChange} />
</Provider>
);
export default App;
The RootNavigation.js file, but it is for our earlier commits not now. I don't put the newer version because of its complexities:
import { createSwitchNavigator } from 'react-navigation';
import { Loading, Dashboard, SignInStack, ListingManagement } from './screens';
const RootNavigation = createSwitchNavigator(
{
Loading,
SignInStack,
Dashboard,
ListingManagement
},
{
initialRouteName: 'SignInStack'
}
);
export default RootNavigation;
And at last, the earlier version of package.json:
{
"name": "sheypoor",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"android": "npx react-native run-android",
"ios": "npx react-native run-ios",
"physical-android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res",
"test": "jest",
"eslint": "eslint .",
"clean": "react-native-clean-project",
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": [
"eslint --fix ."
]
},
"dependencies": {
"formik": "^1.3.0",
"lint-staged": "^7.3.0",
"prop-types": "^15.6.2",
"react": "16.5.0",
"react-native": "0.57.1",
"react-native-confirmation-code-field": "^1.2.2",
"react-native-vector-icons": "^5.0.0",
"react-navigation": "^2.16.0",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"yup": "^0.26.6"
},
"devDependencies": {
"babel-eslint": "^9.0.0",
"babel-jest": "23.6.0",
"babel-plugin-module-resolver": "^3.1.1",
"babel-plugin-root-import": "^6.1.0",
"eslint": "^5.5.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-config-prettier": "^3.0.1",
"eslint-import-resolver-babel-plugin-root-import": "^1.1.1",
"eslint-plugin-flowtype": "^2.50.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-prettier": "^2.6.2",
"eslint-plugin-react": "^7.11.1",
"eslint-plugin-react-native": "^3.3.0",
"eslint-plugin-sort-imports-es6-autofix": "^0.3.0",
"flow-bin": "^0.78.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.45.6",
"prettier": "^1.14.3",
"react-native-clean-project": "^3.0.0",
"react-native-config": "^0.11.5",
"react-test-renderer": "16.5.0",
"redux-devtools-extension": "^2.13.5"
},
"jest": {
"preset": "react-native"
},
"rnpm": {
"assets": [
"./app/assets/fonts"
]
}
}
With these codes and configurations, we didn't give even one error.
In the ReactActivity.java one can check for Bundle savedInstanceState
... in order to control when the React application is being instanced:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* it's always NULL on first run */
if (savedInstanceState == null) {
Bundle initialProperties = new Bundle();
initialProperties.putString("loginToken", HJSession.getSession().getSessionId());
initialProperties.putString("username", HJSession.getSession().getUserName());
initialProperties.putString("userId", HJSession.getSession().getUserId().toString());
String moduleName = "topics";
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
moduleName = bundle.getString("moduleName");
try {
String extra = bundle.getString("extra");
initialProperties.putString("extra", extra);
} catch (Exception e) {
Crashlytics.logException(e.getMessage());
Log.e("ReactActivity", e.getMessage());
}
}
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setJSMainModulePath("index")
.addPackages(Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),
new RNFirebaseMessagingPackage(),
new RNFirebaseNotificationsPackage(),
new RNI18nPackage(),
new VectorIconsPackage(),
new HJRNPackages(),
new NativeNavigationPackage()
))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, moduleName, initialProperties);
setContentView(mReactRootView);
}
}

Categories