I tried using both bootstrap and react-bootstrap but to no avail. I tried something simple like a button but every time I get a whitescreen and 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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
What could be the issue?
CODE:
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
export class Home extends Component {
static displayName = Home.name;
state = {
data: []
};
componentDidMount() {
fetch('/api/weeks')
.then(res => res.json())
.then(data => this.setState({ data }))
.catch(error => console.error(error));
}
render () {
const { data } = this.state;
return (
<div>
<h1>Hello, world!</h1>
<Button>Test</Button>
<button>Test</button>
<h2>Weeks Data</h2>
<ul>
{data.map(week => (
<li key={week.id}>{week.name}</li>
))}
</ul>
</div>
);
}
}
EDIT:
I get the following errors, I don't know what i'm supposed to look at:
Uncaught TypeError: Cannot set properties of undefined (setting '_element') at Button (fails.js:7:1)
VM231 react_devtools_backend.js:4012 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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
The above error occurred in the component
Related
Everytime i use react bootstrap component it doesn't work and gives invalid hook error.
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
function ShowProducts() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<div className="App">
<p>Working</p>
<Button>Test</Button>
</div>
)
}
export default ShowProducts;
it gives following in console:
react.development.js:209 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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
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.
I am trying to add a drop down calendar but I get warning from the code below and
there is not drop down calendar when cursor was placed over the input box.
Warning from the developer tool, console panel:
VM2542 react-dom.development.js:86 Warning: componentWillReceiveProps has been renamed, and >is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.
Move data fetching code or side effects to componentDidUpdate.
If you're updating state whenever props change, refactor your code to use memoization
techniques or move it to static getDerivedStateFromProps. Learn more at: >https://reactjs.org/link/derived-state
Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all >deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe->lifecycles in your project source folder.
Please update the following components: DateInput
ExpenseForm.js
import React from "react";
import moment from "moment";
import 'react-dates/lib/css/_datepicker.css'
import 'react-dates/initialize';
import { SingleDatePicker } from "react-dates";
export default class ExpenseForm extends React.Component {
state = {
createdAt: moment(),
calendarFocused: false
}
onDateChange = (createAt) => {
this.setState(()=>({createAt}))
}
onFocusChange = ({focused}) => {
this.setState(()=>{calendarFocused: focused})
}
render(){
return (
<div>
<SingleDatePicker
date={this.state.createdAt} // momentPropTypes.momentObj or null
onDateChange={this.onDateChange} // PropTypes.func.isRequired
focused={this.state.calendarFocused} // PropTypes.bool
onFocusChange={this.onFocusChange} // PropTypes.func.isRequired
numberOfMonths={1}
isOutsideRange={()=>false}
/>
<button>Submit</button>
</div>
)
}
}
I am also getting a hint warning on VSCode on the line:
import 'react-dates/initialize';
Could not find a declaration file for module 'react-dates/initialize'. 'c:/Users/PEI WAI LEE/Programming/ReactCourse/my-provider/node_modules/react-dates/initialize.js' implicitly has an 'any' type.
If the 'react-dates' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react-dates'ts(7016)
I change this line
onFocusChange = ({focused}) => {
this.setState(()=>{calendarFocused: focused})
}
to
onFocusChange = ({focused}) => {
this.setState(()=>({calendarFocused: focused}))
}
without the brackets the statement won't return calendarFocused
The calendar is now showing when I hover the cursor to the input box
can someone advise the warning and the hit warning on VSCode?
I'm trying to use the Link component in #fluentui/react, but I get an error about invalid hook calls. I tried using Link in office-ui-fabric-react, but got same hook error.
Background:
Component A calls the code with the Link component.
Component A is in a different folder than Link component.
Error:
"react-dom.development.js:3198 Error: 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:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app"
Link code:
import * as React from "react";
import { Link } from "#fluentui/react";
//import { Link } from "office-ui-fabric-react";
export interface ITestProps {
what: string;
click: () => void;
}
export default class TestComponent extends React.PureComponent<ITestProps, {}> {
constructor(props: ITestProps) {
super(props);
}
render() {
return (
<div>
Test {this.props.what}
<button onClick={this.props.click}>Click</button>
<Link onClick={this.props.click}>Click link</Link> <-- this is what is causing hook problems
</div>
);
}
}
Then I tried using a functional component rather than extending from React.PureComponent, but same hook error:
export default function TestComponent(props: ITestProps) {
return (
<div>
Test2 {props.what}
<button onClick={props.click}>Click</button>
<Link onClick={props.click}>Click link</Link> <-- also produces hook error
</div>
);
}
The only way that I solved this problem is my Link code inside the same folder as the Component that uses the Link code.
I want to be able to put my Link code in a separate folder, not in the same folder as Component A.
I also made sure that the react and react-dom version of both folders are the same, but I still got hook errors.
Please any suggestions?
Trying to test the Material-UI Slider with Reat-Test-Renderer gets an error: Uncaught [TypeError: Cannot read property 'addEventListener' of null]
Codesandbox Link
import React from "react";
import { Slider } from "#material-ui/core";
import renderer from "react-test-renderer";
it("should render", () => {
renderer.create(<Slider />);
});
This is not the case with any other Material UI components that I know of.
It seems to be related to forwardRef as described here, but I could not figure out a way to get it to work.
EDIT Unfortunately switching over to #testing-library/react is not an option this project I'm working on.
EDIT 2 The reason I am doing this is because I am trying to render and test a more complex component of my own which contains the Slider. It took me a while to figure out that this is what's causing the issue, and the code above is the minimal amount of code to replicate the issue.
EDIT 3 Error message screenshot
React Test Renderer only renders the components as a JS object rather than to a browser environment. Hence, anything that uses dom based refs will have this issue. Related jest issue: https://github.com/facebook/jest/issues/5462.
There is a section in the React Docs for a way to workaround it: https://reactjs.org/docs/test-renderer.html#ideas
EDIT:
Here's a working test. It likely makes a lot of the functionality of the slider not work, since we are setting the internal refs to null. But it does run. The "Next" branch on MUI doesn't have the findDOMNode function there, so that might be easier to work with.
I wasn't able to get these to work on CodeSandbox because jest was undefined, and I couldn't find how to fix that.
import React from 'react';
import { Slider } from '#material-ui/core';
import renderer from 'react-test-renderer';
jest.mock('react-dom', () => ({
// the useIsFocusVisible function in Slider.js (MUI component) uses findDOMNOde
// Luckily it checks if there's nulls, so we can return a null
// https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/utils/useIsFocusVisible.js#L136
findDOMNode: () => null,
}));
it('should render', () => {
renderer.create(<Slider />);
});
If you want to try and mock the full functionality (sort of), you can use this implementation of the findDOMNode mock, which will return the values that are needed for the useIsFocusVisible to run successfully including adding the event listener:
import React from 'react';
import { Slider } from '#material-ui/core';
import renderer from 'react-test-renderer';
jest.mock('react-dom', () => ({
// the useIsFocusVisible function in Slider.js (MUI component) uses findDOMNOde
// https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/utils/useIsFocusVisible.js#L136
findDOMNode: (instance) => {
return { ownerDocument: instance };
},
}));
it('should render', () => {
let eventListenerFn = jest.fn();
renderer.create(<Slider />, {
createNodeMock: (element) => {
if (element.type === 'span') {
return {
addEventListener: eventListenerFn,
};
}
},
});
});
In order to figure out how to get these tests to succesfully run, I had to step through the error stacks/MUI source code to find out what's going wrong and what values were needed to be mocked in order to not throw errors.
Original, showing how much better #testing-library is for this:
However, may I suggest using #testing-library? It's nice to work with and uses jsdom to render the components so it'll work with this component.
I went ahead and made a couple of random tests for the Slider using the testing library to show that it works with Slider and throws no errors:
import React from "react";
import { Slider } from "#material-ui/core";
import { render } from "#testing-library/react";
it("should render", () => {
render(<Slider />);
});
it("should render an input", () => {
const component = render(<Slider />);
const input = component.baseElement.querySelector("input");
expect(input).toBeDefined();
});
it("Should have the correct value", () => {
const component = render(<Slider value={50} />);
const input = component.baseElement.querySelector("input");
expect(input.value).toBe("50");
});
CodeSandbox
I am using NextJS for server side rendering & I am trying to use useState hook inside a component which is throwing :
Error:
Error: 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
My code:
import { useState } from 'react';
const Banner = ({ movies }) => {
const [movie, setMovie] = useState(movies);
return (
<header>
<h1> Banner </h1>
</header>
)
}
export default Banner;
Directory Tree
/components/Banner.js
/pages
Getting same error when i use useEffect() like :
import React, {useEffect} from 'react'