React Hooks Error

If you are seeing the error below when creating custom components in WebViewer, it is probably due to the fact that you are using React Hooks in your component, or using a library that uses React Hooks.

1Error: 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:
21. You might have mismatching versions of React and the renderer (such as React DOM)
32. You might be breaking the Rules of Hooks
43. You might have more than one copy of React in the same app
5See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

To fix this error, refactor your component to be a class based component rather than a functional component.

Here is an example of a functional component that uses React Hooks:

JavaScript

1const CustomButton = () => {
2 useEffect(() => {
3 console.log('test');
4 }, []);
5
6 return <button>Click me!</button>;
7}
8
9const newCustomElement = {
10 type: 'customElement',
11 dataElement: 'customElementButton',
12 render: () => <CustomButton />
13};
14
15instance.UI.setHeaderItems(header => {
16 header.push(newCustomElement);
17});

Here is an example of a class based component that does the same thing:

JavaScript

1class CustomButton extends React.Component {
2 componentDidMount() {
3 console.log('test');
4 }
5
6 render() {
7 return <button>Click me!</button>;
8 }
9}
10
11const newCustomElement = {
12 type: 'customElement',
13 dataElement: 'customElementButton',
14 render: () => <CustomButton />,
15};
16
17instance.UI.setHeaderItems(header => {
18 header.push(newCustomElement);
19});

The reason hooks don't work for custom component

In WebViewer we use a different instance of React than the one you are using in your app. For hooks to work, the React instance where the hook was declared and where it was rendered must be the same. This is a limitation of React mentioned here: https://react.dev/warnings/invalid-hook-call-warning#duplicate-react

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales