DEV Community

Discussion on: How to add search to your Gatsby site

Collapse
bellons91 profile image
Davide Bellone

Great article! Thank you! I'm going to add search to my blog as soon as possible! :)

Collapse
emma profile image
Emma Goto 🍙 Author

You're welcome! Keen to see it in action!

Collapse
bellons91 profile image
Davide Bellone

I'm trying your solution, but I keep having an error about the usage of useState.
My index page derives from a component:

import React, { useState } from 'react';
//other imports

export default class IndexPage extends React.Component<PageProps> {
  public render() {
    // many things
    const { search } = window.location;
    const query = new URLSearchParams(search).get('s'); 
    const [searchQuery, setSearchQuery] = useState(query || '');
Enter fullscreen mode Exit fullscreen mode

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..

class Bad3 extends React.Component {
  render() {
    // 🔴 Bad: inside a class component
    useEffect(() => {})
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

So, how would you solve it?

Thread Thread
emma profile image
Emma Goto 🍙 Author

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:

const IndexPage = (pageProps) => {
    const { search } = window.location;
    const query = new URLSearchParams(search).get('s'); 
    const [searchQuery, setSearchQuery] = useState(query || '');
}

export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

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 :)