How can i ignore react warnings? (Not Native app) - reactjs

I get this warring in my react app.
It says componentWillReceiveProps has been renamed...
But I don't have "componentWillReceiveProps" in my code only effects ...
Maybe it is inside in node modules.
So i trying to ignore them
But i don't know how...
I used create-react-app
And i am using ts-lint.

Largely inspired from this answer
const error = console.error;
function logError(...parameters) {
let filter = parameters.find(parameter => {
return (
// Filter error because XXX
parameter.includes("Warning: %s is deprecated in StrictMode")
// Another error to filter because of YYYY
|| parameter.includes("Warning:")
);
});
if(!filter) error(...parameters);
}
console.error = logError;
Note that this code only works for errors, but you can duplicate it for console.warn or info
You can manage this in a particular .js file, and import it in the App.js

By using below code you can hide the desirable warnings
import React from 'react';
import { YellowBox } from 'react-native';
import AppNavigator from './app/main';
YellowBox.ignoreWarnings([
'Warning: isMounted(...) is deprecated',
'Module RCTImageLoader',
'Class RCTCxxModule',
'Task orphaned for request ',
'Warning',
'Require',
'Missing field __typename in',
'Node',
]);
const App = () => <AppNavigator />;
export default App;

Related

Laravel + InertiaJS + ReactJS Components Renders Twice

So I am currently developing a web application and noticed that some of my components renders twice and I am not really sure why and also that console.log appears twice in the console. I am sure that I am only calling the console.log once and the toast once.
I have read about the strict mode in reactjs but I am unsure if it is enabled or not since I can't find it in my source code.
Here's my app.jsx
import '../css/bootstrap/bootstrap.min.css';
import '../css/bootstrap-icons-1.10.3/bootstrap-icons.css'
import '../css/dhca-base.sass'
import React from 'react';
import { createInertiaApp } from '#inertiajs/react'
import { createRoot } from 'react-dom/client'
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
return pages[`./Pages/${name}.jsx`]
},
setup({ el, App, props }) {
createRoot(el).render(<App {...props} />)
},
})
I also have the reactjs development extensions in my browser and it shows me a warning sign near the Inertia title.
Turns out everything is set up correctly and I was just not using the useEffect hook correctly.

If possible, how to use MUI with Qwik framework?

I try Qwik framework which looks a lot like Reactjs and uses jsx. And suddenly, I wonder if Reactjs libraries such as MUI can work with Qwik framework.
I tried this code:
import { component$ } from "#builder.io/qwik";
import Add from "#mui/icons-material/Add";
import IconButton from "#mui/material/IconButton";
const AddToCartButton = component$(() => {
return (
<IconButton>
<Add />
</IconButton>
);
});
export default AddToCartButton;
But I got this this error:
QWIK ERROR Code(25): Invalid JSXNode type. It must be either a function or a string. Found: {
'$$typeof': Symbol(react.memo),
type: {
'$$typeof': Symbol(react.forward_ref),
render: [Function: Component] { displayName: 'AddIcon', muiName: 'SvgIcon' }
},
compare: null
} Error: Code(25): Invalid JSXNode type. It must be either a function or a string. Found:
at logError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4515:58)
at logErrorAndStop (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4521:21)
at qError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4585:16)
at Proxy.jsx (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:605:23)
at AddToCartButton_component_4S0nJgnxzBU (/src/addtocartbutton_component_4s0njgnxzbu.js:11:55)
at useInvoke (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:149:30)
at E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4676:32
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async renderSSR (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:5280:9)
at async Proxy.renderToStream (E:\qwik\flower\node_modules\#builder.io\qwik\server.cjs:582:3)
at async file:///E:/qwik/flower/node_modules/#builder.io/qwik/optimizer.mjs:1776:30
QWIK ERROR Code(25): Invalid JSXNode type. It must be either a function or a string. Found: Error: Code(25): Invalid JSXNode type. It must be either a function or a string. Found:
at logError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4515:58)
at logErrorAndStop (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4521:21)
at qError (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4585:16)
at Proxy.jsx (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:605:23)
at AddToCartButton_component_4S0nJgnxzBU (/src/addtocartbutton_component_4s0njgnxzbu.js:11:55)
at useInvoke (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:149:30)
at E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:4676:32
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async renderSSR (E:\qwik\flower\node_modules\#builder.io\qwik\core.cjs:5280:9)
at async Proxy.renderToStream (E:\qwik\flower\node_modules\#builder.io\qwik\server.cjs:582:3)
at async file:///E:/qwik/flower/node_modules/#builder.io/qwik/optimizer.mjs:1776:30
not rendered
JSX in this case is the templating language of Qwik but the underlyings are different. It is made similar so you have an easier transition from react as stated in their docs.
Qwik is familiar for React developers and can be used to build any type of web site or application.
Qwik offers some adapter for react components you need to install and wrap your components in.
npm i -D #builder.io/qwik-react
And then the usage should look like the example in their repo.
/** #jsxImportSource react */
import { qwikify$ } from '#builder.io/qwik-react';
import { Button } from '#mui/material';
export const App = qwikify$(() => {
return (
<>
<Button variant="contained">Hola</Button>
</>
);
});
This thread is a bit older but maybe someone stumbles across it like me.
I had the same issue using a UI-component library and resolved it with the following steps.
adding qwikReact into the vite.config file:
import { defineConfig } from "vite";
import { qwikVite } from "#builder.io/qwik/optimizer";
import { qwikCity } from "#builder.io/qwik-city/vite";
import { qwikReact } from "#builder.io/qwik-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig(() => {
return {
plugins: [qwikCity(), qwikVite(), qwikReact(), tsconfigPaths()],
preview: {
headers: {
"Cache-Control": "public, max-age=600",
},
},
};
});
qwikify() must be used in a seperate file only with /** #jsxImportSource react */ as Jonathan pointed out.
Be aware that react components will not be treated the same way in Qwik. As stated in the docs it should be a migration/testing tool for existing projects where react components should be introduced in "Wide islands".
For those of you who are using Qwik Speak for I18N, the proposed solution will not work as is because Qwik-Speak won't be able to handle the JSX. The solution is to individually wrap the MUI component and then use it normally as so:
import { component$ } from "#builder.io/qwik";
import { Link } from "#builder.io/qwik-city";
import { $translate as t, Speak } from "qwik-speak";
import Button from "#mui/material/Button";
import { qwikify$ } from "#builder.io/qwik-react";
export const MUIButton = qwikify$(Button);
export default component$(() => {
return (
<Speak assets={["welcome"]}>
<div>
<h1>{t("welcome.title##Welcome")}</h1>
<MUIButton variant="contained">Do Something</MUIButton>
</div>
</Speak>
);
})

recoil: Duplicate atom key - in nextjs

I do use recoil in my nextjs application.
But if I run next (in dev or production make no difference) I got this error-message:
Duplicate atom key "companyData". This is a FATAL ERROR in
production. But it is safe to ignore this warning if it occurred because of
hot module replacement.
This is the way I've implemented it:
/src/stores/CompanyStore.js:
import { useSetRecoilState, useRecoilValue , atom } from 'recoil';
import config from '../../content/config.yml';
const companyData = atom({
key: 'companyData',
default: {...config.company},
});
export const useSetCompanyData = () => useSetRecoilState(companyData);
export const useCompanyData = () => useRecoilValue(companyData);
export default {
useSetCompanyData,
useCompanyData,
};
I use it like this in some components:
MyComponent.js
import React from 'react';
...
...
import {useCompanyData} from '../stores/CompanyStore';
const MyComponent = () => {
const classes = useStyles();
const companyData = useCompanyData();
const { summary: headline, description } = companyData;
return (<div><h2>{headline}</h2><p>{description}</p>)
I don't see, why this error-message appears. Might it caused of a bug in nextjs, or did I implement recoil in a wrong way?
Looks like a problem with recoil in nextjs when you have state in a separate file:
https://github.com/facebookexperimental/Recoil/issues/733
As of Recoil 0.7.6, add RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED=false to your environment to hide these warnings.
(roeland had the correct GitHub issue, which has since been closed)

How to use stripe library on tsx files. Getting error

I have a project which is on react but files are not .js instead they are .tsx and I am trying to use stripe library but keep getting error.
I have tried few different libraries which help setting up stripe but I am keep getting stuck on this errr.
Please help or direct me to correct library which help me setup stripe.
my codes are
import ReactDOM from "react-dom";
import StripeCheckout from 'react-stripe-checkout';
import axios from "axios";
function handleToken(token, addresses) {
console.log(token, addresses);
}
export default function Webinar() {
return (
<div className="container">
<StripeCheckout stripeKey = "mykey"
token={handleToken}
name="Tesla Roadster"
billingAddress
shippingAddress
/>
</div>
);
}
The problem is saying that your Typescript repo is now strict mode enabled which forces you specify the typing. If you wish to keep it silent, you can simply switch it to false in tsconfig.json:
{
"compilerOptions": {
"strict": false,
// ...
}
}
Change your function handleToken to be a variable with has the same type of your component prop as following:
const handleToken: StripeCheckout['props']['token'] = (token) => {
// You can receive hint from token type here
}

How do I add an event listener to a React component?

I'm trying to build a React web app (v 16.13.0). I want a flash message component, to display status after a form is submitted. If there is already something standard, that would be preferable, but since I can't find anything, I'm trying to roll my own using this -- https://medium.com/#jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53 . Here's the component
import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';
import './index.css';
export const Flash = () => {
let [visibility, setVisibility] = useState(false);
let [message, setMessage] = useState('');
let [type, setType] = useState('');
useEffect(() => {
Bus.addListener('flash', ({message, type}) => {
setVisibility(true);
setMessage(message);
setType(type);
setTimeout(() => {
setVisibility(false);
}, 4000);
});
}, []);
useEffect(() => {
if(document.querySelector('.close') !== null) {
document.
querySelector('.close').
addEventListener('click', () => setVisibility(false));
}
})
return (
visibility && <div className={`alert alert-${type}`}>
<span className="close"><strong>X</strong></span>
<p>{message}</p>
</div>
)
}
Problem is, web site uses custom code, but doesn't show source for
Bus.addListener('flash', ({message, type}) => {
setVisibility(true);
setMessage(message);
setType(type);
setTimeout(() => {
setVisibility(false);
}, 4000);
});
so my question is, how do I add an event listener to a React component?
Edit: In response to the answer given, I created this file ...
localhost:client davea$ cat src/Utils/Bus.js
import EventEmitter from 'events';
export default new EventEmitter();
but re-compiling my module results in this error ...
./src/components/Flash/index.js
Module not found: Can't resolve '../Utils/Bus' in '/Users/davea/Documents/workspace/chicommons/maps/client/src/components/Flash'
These are the first lines of the file above. Note the second "import" where I'm importing "Bus" ...
import React, { useEffect, useState } from 'react';
import Bus from '../Utils/Bus';
import './index.css';
export const Flash = () => {
The website included the code: https://medium.com/#jaouad_45834/building-a-flash-message-component-with-react-js-6288da386d53
To set that up, we need to create a new folder in our root directory and name it Utils and create on it a Bus.js file with will contains the following code:
import EventEmitter from 'events';
export default new EventEmitter();
This is all Bus.js is, a simple event emitter.
You can also use react-toastify or useToasts for this.
In order to show the flash message, you need to do something like the following.
Bus.emit('flash', {type: 'danger', message: 'error occurred'});
I have used the code you have provided and mixed it with a dummy form. Upon submitting the form, the flash message appears successfully.
Live example & working code is here:
https://codesandbox.io/s/dazzling-lamarr-k3cn5
Some notes:
I have refactored and removed 2nd useEffect as it is inefficient and unnecessary. The onClick can very well be applied to the close-span-element
If you are using redux, you can use create global Flash/Alert message and connect it to the store. Any redux-connected-component can simply work its own logic and dispatch an alert action and render different types of messages.
Using ready made libraries are also cool.
I think what you want is widely known as a Toaster, and you can use a library like React Toastify [https://github.com/fkhadra/react-toastify] with a simple configuration and high customization

Resources