Cannot read property 'getHostNode' of null - javascript

I have a horizon/react app with react router and I have a simple button in my app:
<Link className="dark button" to="/">Another Search</Link>
When I click on it, I get the following exception:
Uncaught TypeError: Cannot read property 'getHostNode' of null
The error comes from:
getHostNode: function (internalInstance) {
return internalInstance.getHostNode();
},
Any idea why am I getting this?

I was facing a similar issue. It turns out that, in my case, was highlighthjs removing comments from the generated dom.
For text, React 15 is adding comment with the reactid instead of a span tag, as in:
<!-- react-text: 248-->
Another Search
<!--/react-test-->
Can you try something like this?
<Link className="dark button" to="/"><span>Another Search</span></Link>
This will force the generated DOM to include the span with the proper data-reactid attribute.
I would file an issue with react-router, maybe they can do that internally so you would not have to bother about it. But there are challenges with that as the Link child could be basically anything.

I have run into this issue multiple times in the last few days (new to react) and in almost all the cases, there was some syntax/code error that was not caught anywhere else. One example: If you write:
getInitialState() {
showModal: false
},
instead of:
getInitialState() {
return {
showModal: false
};
},
you will get this error. That is unless your build process does not already catch the error. Hope this helps someone (or myself in a couple of days. Hi Niyaz, you are welcome!).

If anyone else finds this thread. For me this turned out to be a null error for a prop.
Code generating error:
<Menu InventoryCount={this.state.inventoryModel.length} />
Working null checked code:
<Menu InventoryCount={this.state.inventoryModel ? this.state.inventoryModel.length : 0} />

For me, it's a typo which results in importing component from wrong module.
import { Link, Icon } from 'react-router';
import { Tag } from 'antd';
it should be
import { Link } from 'react-router';
import { Tag, Icon } from 'antd';

I just had to restart my nodemon backend.

Very interesting :) for me, it turned out that I was consuming props incorrectly in child component. Might be helpful for someone.
function Parent(){
const styleEle = { width: '100px'};
return (<div>
<Child styleO={styleEle}/>
</div>);
}
function Parent(props){
// here i was directly using <div style={styleO}> causing issue for me
return (<div style={props.styleO}>
{'Something'}
</div>)
}

if you getting error like "getHostNode" of null then its a error related to old code which is written before and it comes with version update of react
we have two ways to resolve the same
1) First we have to uninstall react from project and than again install react with the version specified( old one 15.4.2) current version of react is 15.6.1
2) Second way is bit time consuming but for future of application its good , go through the old code and handle errors(error handling of promises ) with the correct way following are few links which help you to figure out whats running behind
https://github.com/facebook/react/issues/8579
https://github.com/mitodl/micromasters/pull/3022

I got this error trying to render undefined value by mistake.
render(){
let name = this.getName(); // this returns `undefined`
return <div>name: {name}</div>
}
The fix is to fallback to null (where is accepted value)
render(){
let name = this.getName(); // this returns `undefined`
return <div>name: {name || null}</div>
}

I have had similar issue.
I was trying to manually update some plugin from node_modules, and when I reverted it back, i got this error.
I solved it by deleting node_modules and running NPM install.

In my case React was not in the scope of the file.
If you import a variable which has jsx from a different file which does not have react imported in it.
import React from "react";
Using following eslint plugin would avoid this: react-in-jsx-scope
Source: https://github.com/yannickcr/eslint-plugin-react/issues/84

In my case, an import was missing. Check your imports!

My solution is just deleting the cached images, files and cookies if you using the Chrome. Settings -> Privacy and security -> Clear browsing data -> Cached image and files / Cookies and other site data

Related

Build System CTA's/Callback function not working

I am working on a build/design system. and everything works fine. The only issue is when I publish my package and attempt to use the callback function. It doesn't properly return the data that is necessary for me to go to the next screen.
I attempted to get a reproducible example for you in CodeSandbox, however, there were some minor implications/errors that wouldn't allow me to get to the specific error I am talking to you about now. That seems to have its own issues.
So, how do you reproduce this error? Well, our package as of right now is public. As said above you can't import into CodeSandbox as it gives other errors on React versions (as said, I will deal with that later..). The package name is #sandboxcommerceeng/react the scss package you might need is #sandboxcommerceeng/scss. Go ahead and import into a CSS file. #import '#sandboxcommerceeng/scss/lib/global.css'. Then in the #sandboxcommerceeng/react package, import ECommercePlatformModal. The code below will give you a reproducible error. Platforms type, is also exported by #sandboxcommerceeng/react
const [showEcommerceModal, setShowEcommerceModal] = React.useState<boolean>(false);
const [url, setUrl] = React.useState<string>('');
const [selectedPlatform, setSelectedPlatform] = React.useState<keyof Platforms>();
<ECommercePlatformModal
selectedPlatform={selectedPlatform}
onSelectPlatform={(platform: keyof Platforms | undefined) =>
setSelectedPlatform(platform)
}
showModal={showEcommerceModal}
onCancel={() => setShowEcommerceModal(false)}
okButtonProps={{ onClick: () => console.log(url) }} // ✴
urlValidated={true}
onUrlChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setUrl(e.target.value);
}}
url={url}
/>
✴: I am unable to get the URL from the state using a callback. I've tried just referencing a callback function separately and then logging the URL from there. I've also tried pasting in the URL from the callback. Nothing is working.
End Goal
The end goal here is to have it so that I am able to apply my package into my React application and have the package functionality, i.e. the javascript code implemented in the package itself, work as expected. Expectation for this particular component, is to be able to console.log the url and have it show in the package from the callback function okButtonProp{{onClick: () => console.log(url)}}
Please let me know if there is anything else you need from me.
Your answer lies here. (it could be just a comment but don't have enough reputation yet :) ).
After debugging, the issue did lay within the build system itself. Using React.memo on a button component was the culprit. The memoization wasn't working as intended due to the fact that none of the props were actually changing on the component, therefore it wasn't re-rendering the button component with the new function and variables being passed down to it.
I went ahead and removed the memoization from the memoized component, as I couldn't see a way to fit memoization in this instance.

Expected server HTML to contain a matching <tag> in <tag>

We are using nextjs and getting this error at page refresh (or first load)
My error is:
react-dom.development.js:88 Warning: Expected server HTML to contain a matching <tag> in <tag>.
The code of our functional component looks like this:
export default MyComponent () {
if(! props.something){ // ← this is causing the problem.
return null;
}
return (
<>
HTML here ...
</>
)
}
From my understanding, SSR is different from client side rendering and this is why react is complaining.
The app is working fine but this error is showing in the console and we don't want to have many errors being thrown there as this may prevent us from seeing the real errors when they happens.
Solution:
The solution is to use dynamic imports and and wrap the component call into:
const MyDynamicComponent = dynamic(() => import('./myComponent'), {ssr: false});
//use it:
<MyDynamicComponent />
//OR :
const MyDynamicComponent = dynamic(() => import('./myComponent'))
//use it:
{typeof window !== 'undefined' && (
<MyDynamicComponent />
)}
May be importing your component dynamically should solve this.
Below is the link you can refer;
https://nextjs.org/docs/advanced-features/dynamic-import
I've been looking for solution of a similar problem, but I was using react-window lib and the problem appeared to be in it. I passed different height to it, depends on whether it's loading on server or client, so it gave me back different elements.
My solution was to pass the same height at the beginning, but to change it to window.innerHeight on useEffect ( = on client load).
When this happened to me on a Next project, I had not nested my html table elements properly. Specifically, didn't wrap my <tr> in a <tbody>
the code is executed first on the server after in the browser in my case this is why i get this error and other error with style component like :
Warning: Prop className did not match. Server: "CardUserInfo....
so this link help :
https://github.com/vercel/next.js/discussions/17443
enter link description here
and the solution for me like montienned in this disscussion implement useState useEffect
const [mount, setMount] = useState(false)
useEffect(() => {
setMount(true)
}, [ ])
return mount&&(
<InfoUserCard/>)
In my case the console error displaying Warning: Expected server HTML to contain a matching <sup> in <span>. using Safari Web Browser in development ONLY, i.e. localhost:3000 . Just get rid of this boring error by using Chrome Web Browser.
This boring error will not be exist in production with Safari Web Browser.

VS Code problem: When I save, rows and spaces add automatically and destroys code

I'm using VS code and when I save, it automatically adds extra spaces and rows in tags and other parts of the code. After I change it back to the previous syntax and save again, this problem repeats and then my code couldn't work.
Recently I changed some property in my settings, I think it is connected to a "Prettier" extension, and since then I have this problem, but I don't remember which one to enable now in order to fix it.
For example here is an original code syntax in JS file:
import React, { useState } from 'react';
function App() {
return ( null);
<div>
</div>
}
export default App;
And this is what happens after I save:
import React, {
useState
} from 'react';
function App() {
return (null); <
div >
<
/div>
}
export default App;
I can't bring it back to correct syntax (delete unnecessary rows and spaces) when I change it back and save again - it does the same thing. I made changes like the offer here (add rewrap) and there (trim settings), but it didn't help.
I tried to uninstall and then reinstall my program, but it didn't help. My VS code version doesn't have the Tools option that may help.
I also faced a similar issue as shown here:
Select "JavaScript React" instead of "JavaScript" as shown here:

How to let react electron ignore undefined error?

React electron on windows, if A is null, call A.test will make the application stop working, then the user has to close the application and restart it.
How to let react ignore the error, and continue work. The code has many A.test, I can't write everywhere if(A) A.test.
If this can't be resolved, can I print the error on the web view? So I don't have to remote visit the user's computer to see the console error.
NOTE
I think the solution is to use react error boundaries, as suggested in the console.
You already pointed out that you're using error boundaries, so after testing your scenarios in this fiddle I believe your implementation might be incorrect.
Given a similar implementation for ErrorBoundary in the docs:
class ErrorBoundary extends React.Component {
state = { hasError: '' };
render() {
return this.state.hasError ? (
<span>Oops! Something went wrong:<br />{this.state.hasError}</span>
) : this.props.children;
}
}
ErrorBoundary.getDerivedStateFromError = (error) => ({ hasError: error.toString() });
This component will render the fallback when any of its children breaks.
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI
It will look similar to:
<MyReactApp>
<ErrorBoundary>
<ChatContent />
</ErrorBoundary>
</MyReactApp>
Now any error in ChatContent will be catch by ErrorBoundary giving you the opportunity to render the fallback like:
Oops! Something went wrong:
ReferenceError: test is not defined
The code has many A.test, I can't write every where if(A) A.test
But why? You can use some editor for multi file editing.
So you can replace A.test() to safeTest(A) function.
export const safeTest = (Obj) => {
if (Obj) {
Obj.test();
} else {
// Any action you want
}
}
It is hard to offer an answer to your question because I don't see your project codes, but if your react version is 16 you can use a special component lifecycle method that name is componentDidCatch.
Inside this method you will have these values:
componentDidCatch(error, info) {
// Do something with error and info
}
Even you can use setState inside this method and show you want. I think this method can help you for your second desire, the printing error in web view.
I tend to favor using default props. You can set a value for the component to assign to a prop if the prop is passed in undefined. For example, if your component depends on an array nested within an object, you could set that value as an empty array by default. This is especially handy when your component depends on an array of results from an API call, but the component renders before the request finishes.
If you want to make the minimal effort to catch all the unhandled errors from both main and renderer processes within Electron as well as showing them to the user via a dialog, the easy way is to use electron-unhandled which does exactly that:
After having installed it (npm i electron-unhandled), in both your main and renderer entry files (likely their root index.js), you just have to add, at the beginning:
const unhandled = require('electron-unhandled');
unhandled({ showDialog: true });
Now, that being said, it's a good practice to use a global error catcher but it's a really bad one if you use only that. You should try covering your error handling more accurately, at least method by method:
.then() { ... }.catch(err => ...) for your promises,
(..., (err, res) => { if (err !== null) { ... } ... ) for your callbacks,
try { ... } catch(err) { ... } for non-async or await-based code code parts.
And, as a side-note, I myself created a dependenciless library to make it safe and easy to create a global errors dictionary in order to well-organize your errors but there are other alternatives if this one doesn't fit your needs.
I guess the best possible solution to this would be surrounding your A.test in try and catch. In this case what you can do is catch the error is A is null and perform some error page from your side incase you want it or just keep the error silent incase you dont want to perform any operation and suppress the error and continue execution.
You can also wrap A.test in a function with try-catch and use that function instead of A.test. In this way you can avoid multiple try-catch block and you can handle the error as per your requirement here.

React: Uncaught TypeError: Cannot read property '_currentElement' of null

I'm having problem rendering a route in React. All I see is the page before React does any rendering to it, and the following error.
Mainly, I'm having trouble figuring out which component/line is causing the error, if anyone can provide some insight I'd appreciate that. Thanks.
Make sure you're importing all components your using inside your render() { ... } block.
This error can be thrown if you're trying to render a component that hasn't been properly imported or is returning undefined.
If this is a case you may also be seeing a related error Uncaught TypeError: inst.render is not a function.
I try to identifying which component is causing the issue by:
Replace jsx with simple <div>test</div> element by element
If I find an element / component causing it, I make sure it is impoted, then dig deeper.
Look at your diff and revert code / stash code
Best of luck!
I had such error when had multiple instances of React required. Is it the case for you?
I frequently see this after any component has let an uncaught exception out of its render() method. Only resolution we've found so far is refreshing the page. 😓
The React GitHub issue #JosiahDaniels linked (#4026) discusses the same behavior: "Some invariant violations leaves React in an unstable state at the moment so this is to be expected." --syranide
The issue is closed, as the onus is on the application author not to disrupt React's rendering cycle with exceptions.
You could forget exporting the component:
var MyComponent = React.createClass({
...
});
module.exports = MyComponent;
Hope that helps.
React v15 added an unstable_handleError function, which can be used to help troubleshoot this sort of issue.
Basic example:
unstable_handleError = (error) => {
console.log(error)
}
More info:
https://medium.com/#blairanderson/handle-react-errors-in-v15-4cedaae757d7#.9moxc4d3z

Categories

Resources