I'm trying your solution, but I keep having an error about the usage of useState.
My index page derives from a component:
importReact,{useState}from'react';//other importsexportdefaultclassIndexPageextendsReact.Component<PageProps>{publicrender(){// many thingsconst{search}=window.location;constquery=newURLSearchParams(search).get('s');const[searchQuery,setSearchQuery]=useState(query||'');
So, when I run the project, I get an error: Invalid hook call. Hooks can only be called inside of the body of a function component.
The official React documentation states that this error is due to the fact that I'm running this code inside a React Component..
classBad3extendsReact.Component{render(){// 🔴 Bad: inside a class componentuseEffect(()=>{})// ...}}
Great article! Thank you! I'm going to add search to my blog as soon as possible! :)
You're welcome! Keen to see it in action!
I'm trying your solution, but I keep having an error about the usage of
useState
.My index page derives from a component:
So, when I run the project, I get an error: Invalid hook call. Hooks can only be called inside of the body of a function component.
The official React documentation states that this error is due to the fact that I'm running this code inside a React Component..
So, how would you solve it?
Yes, so you can write a React component in one of two ways: as a functional component (the "newer" way), and as a class component.
You could convert your class component to a functional component:
And that would let you use the useState hook. You can still use class components, but I think it makes things a little bit more complicated :)