Invalid hook call. ReacJs

Viewed 86

I have been troubleshooting this error for hours now. I'm using the hooks on top of a function (getItems). i don't know what mistake i have done. How should i clear this?

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 See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

`

App.js

import React from "react";

const data = {
list: [
  {
    id: 0,
    title: "A1",
    list: [
      {
        id: 3,
        title: "A2",
      },
    ]
  },
]
 };
  function getItems() {
    const [menuStack, setStack] = React.useState([data.list]);

    const pushState = (list) => {
        list && setStack((stack) => [...stack, list]);
    };
    const popState = () => {
        menuStack.length > 1 && setStack((stack) => stack.slice(0, -1));
    };

    const top = menuStack[menuStack.length - 1];
    return (
        <button onClick={popState}>BACK</button>
    );

}
export default class PopUp extends React.Component {
render() {
    return (
        <div>
            {getItems()}
        </div>
    );
}
}

Index.js

import React from "react";
export default class Home extends React.Component {
render(){
 return (
 <App />
  );
 }
} 
3 Answers

You are calling function getItems inside your PopUp component and expecting to print the output. React treat that function as a normal function and hence throws that error.

You need to tell react that this is a component function by doing

<div>
<getItems />
</div>

The issue is with class getItems, You can use that as a Component. <GetItems />

import React from "react";

const data = {
  list: [
    {
      id: 0,
      title: "A1",
      list: [
        {
          id: 3,
          title: "A2",
        },
      ],
    },
  ],
};
function GetItems() {
  const [menuStack, setStack] = React.useState([data.list]);

  const pushState = (list) => {
    list && setStack((stack) => [...stack, list]);
  };
  const popState = () => {
    menuStack.length > 1 && setStack((stack) => stack.slice(0, -1));
  };

  const top = menuStack[menuStack.length - 1];
  return <button onClick={popState}>BACK</button>;
}

export default class PopUp extends React.Component {
  render() {
    return (
      <div>
        <GetItems />
      </div>
    );
  }
}

In react, hooks can be written in functional components. But you called getItems function as a general function, not a functional component.

You should let react treat as a component like following:

<getItems />
Related