Skip to content

Instantly share code, notes, and snippets.

@Neeraj1005
Created April 24, 2021 15:57
Show Gist options
  • Save Neeraj1005/d8829eba64c8ee7c1096d2312610be59 to your computer and use it in GitHub Desktop.
Save Neeraj1005/d8829eba64c8ee7c1096d2312610be59 to your computer and use it in GitHub Desktop.
Create Search in Nextjs and using strapi API

create component Search.js

import { useState } from "react";
import { useRouter } from "next/router";
import styles from "@/styles/Search.module.css";

export default function Search() {
  const [keyword, setKeyword] = useState("");

  const router = useRouter();

  const handleSubmit = (e) => {
    e.preventDefault();
    router.push(`/events/search?term=${keyword}`);
    setKeyword("");
  };

  return (
    <div className={styles.search}>
        {keyword}
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={keyword}
          onChange={(e) => setKeyword(e.target.value)}
          placeholder="Search Events"
        />
      </form>
    </div>
  );
}

create a file pages/events/search.js

import Layout from "@/components/Layout";
import EventItem from "@/components/EventItem";
import { API_URL } from "@/config/index";
import { useRouter } from "next/router";
import qs from "qs";
import Link from "next/link";

export default function SearchPage({ events }) {
  const router = useRouter();
  return (
    <Layout>
        <Link href='/events'>
            Go Back
        </Link>
      <h1>Search Result For {router.query.term}</h1>
      {events.length === 0 && <h3>No events to show</h3>}

      {events.map((evt) => (
        <EventItem key={evt.id} evt={evt} />
      ))}
    </Layout>
  );
}

export async function getServerSideProps({ query: { term } }) {
  const query = qs.stringify({
    _where: {
      _or: [
        { name_contains: term },
        { performers_contains: term },
        { description_contains: term },
        { venue_contains: term },
      ],
    },
  });

  const res = await fetch(`${API_URL}/events?${query}`);
  const events = await res.json();

  return {
    props: { events },
  };
}

and add your search component where you want to show in my case it is on header

import Link from "next/link";
import styles from "@/styles/Header.module.css";
import Search from "@/components/Search";

export default function Header() {
  return (
    <header className={styles.header}>
      <div className={styles.logo}>
        <Link href="/">
          <a>DJ Events</a>
        </Link>
      </div>
      <Search />
      <nav>
        <ul>
          <li>
            <Link href="/events">
              <a>Events</a>
            </Link>
          </li>
        </ul>
      </nav>
    </header>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment