website-logomedCode

Next.js : Search & filtering in Server side Components

Learn how to implement Next.js search in Server Components efficiently. Get step-by-step tips to enhance your app's performance and UX.
MOHAMMED DAKIR| October 9, 2024
next.js
Next.js : Search & filtering in Server side Components

#Next.js #filtering #Search #Sever

Introduction

In modern web development, server components and search parameters are essential for optimizing performance and enhancing user experience. React and Next.js, two of the most popular frameworks, offer robust solutions for implementing these features efficiently. This blog post will delve into the intricacies of server components, search parameters, React server components, Next.js search in server components, and filtering in server components.

Understanding Server Components

Server components are a crucial aspect of modern web applications. They enable developers to offload rendering to the server, reducing client-side load and improving application performance. By rendering components on the server, we can take advantage of server resources and deliver fully-rendered HTML to the client, leading to faster load times and a smoother user experience.

Benefits of Server Components

  1. Improved Performance: By rendering components on the server, the initial load time is significantly reduced.
  2. SEO Optimization: Server-rendered HTML is more easily indexed by search engines, improving SEO.
  3. Reduced Client-Side Complexity: Offloading rendering to the server simplifies the client-side code.

Search Parameters in Server-Side Rendering

Search parameters are essential for dynamic content rendering based on user input. They allow the server to generate content based on query parameters, enhancing the flexibility and interactivity of web applications.

1.create nextjs app by this commande :
npx create-next-app\n
2.create folder inside app directory app/blogs/page.jsx
3.inside api directory create search folder and create route.js

\"nextjs

note: articles folder is an example of rest API for get data from MongoDB

this is a route.js for search API :

import Article from \"@/app/module/Article\";\nimport connect from \"@/app/utils/ConnectDB\";\nimport { NextResponse } from \"next/server\";\n\nexport const GET = async (request) => {\n  const url = new URL(request.url);\n  const query = url.searchParams.get(\"query\");\n  console.log(\"search query\", query);\n  try {\n    await connect();\n    const articles = await Article.find();\n    const filterArticles = articles.filter((item) => {\n      return item.title.toLowerCase().includes(query.toLowerCase());\n    });\n\n    return new NextResponse(JSON.stringify(filterArticles), { status: 200 });\n  } catch (error) {\n    return new NextResponse(\"error database\", { status: 500 });\n  }\n};\n
4.create component folder and inside it create a search.jsx file
\"use client\";\nimport React, { useEffect, useState } from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport Image from \"next/image\";\n\n\nconst SearchBar = () => {\n  const [posts, setPosts] = useState([]);\n  const [query, setQuery] = useState(\"\");\n  const router = useRouter();\n  \n  const onChangeHandle = (query) => {\n    const filteredPosts = posts.filter((post) => {\n      const regex = new RegExp(`${query}`, \"gi\");\n      return post.title.match(regex);\n    });\n    setQuery(query);\n  };\n  const handleSearch = async (e) => {\n    e.preventDefault();\n    const res = await fetch(`/api/articles/search?query=${query}`, {\n      cache: \"no-store\",\n    });\n    if (!res.ok) {\n      return alert(\"No results found\");\n    }\n    const searchResult = await res.json();\n    if (searchResult.length ==!) {\n      const firstResultId = searchResult[0].slug;\n      router.push(`/blogs/${firstResultId}`);\n    }\n  };\n  useEffect(() => {\n    const handleSearch = async () => {\n      try {\n        const res = await fetch(`/api/posts`, {\n          cache: \"no-store\",\n        });\n\n\n        if (!res.ok) {\n          throw new Error(\"No results found\");\n        }\n\n\n        const fetchedPosts = await res.json();\n        setPosts(fetchedPosts);\n      } catch (error) {\n        console.error(error);\n      }\n    };\n    handleSearch();\n  }, []);\n  return (\n    <>\n      <form\n        onSubmit={handleSearch}\n        className=\"mt-6 px-4 py-2 rounded-full max-w-2xl bg-gray-50 border flex focus-within:border-gray-300 lg:ml-12 xs:ml-0 xs:px-2 xs:py-1 dark:bg-dark dark:border-light dark:shadow-light\"\n      >\n        <input\n          type=\"text\"\n          placeholder=\"Search for components & templates...\"\n          value={query}\n          onChange={(e) => onChangeHandle(e.target.value)}\n          className=\"bg-transparent w-full focus:outline-none font-semibold border-0 focus:ring-0 px-0 py-0\"\n          name=\"topic\"\n        />\n        <button\n          type=\"submit\"\n          name=\"search-button\"\n          title=\"search-button\"\n          aria-labelledby=\"search-button\"\n          className=\"flex flex-row items-center hover:bg-cyan-600 justify-center px-4 rounded-full border disabled:cursor-not-allowed disabled:opacity-50 transition ease-in-out duration-150 text-base bg-mainColor text-white font-medium tracking-wide border-transparent py-1 h-[38px]\"\n        >\n          <svg\n            className=\"text-gray-200 h-5 w-5 p-0 fill-current hover:text-gray-600\"\n            xmlns=\"http://www.w3.org/2000/svg\"\n            xmlnsXlink=\"http://www.w3.org/1999/xlink\"\n            version=\"1.1\"\n            x=\"0px\"\n            y=\"0px\"\n            viewBox=\"0 0 56.966 56.966\"\n            style={{ enableBackground: \"new 0 0 56.966 56.966\" }}\n            xmlSpace=\"preserve\"\n          >\n            <path d=\"M55.146,51.887L41.588,37.786c3.486-4.144,5.396-9.358,5.396-14.786c0-12.682-10.318-23-23-23s-23,10.318-23,23  s10.318,23,23,23c4.761,0,9.298-1.436,13.177-4.162l13.661,14.208c0.571,0.593,1.339,0.92,2.162,0.92  c0.779,0,1.518-0.297,2.079-0.837C56.255,54.982,56.293,53.08,55.146,51.887z M23.984,6c9.374,0,17,7.626,17,17s-7.626,17-17,17  s-17-7.626-17-17S14.61,6,23.984,6z\" />\n          </svg>\n        </button>\n      </form>\n    </>\n  );\n};\n
5.wrap searchbar.jsx inside blogs folder page.jsx
import React from \"react\nimport SearchBar from \"./component/Search\"\n \nexport default function page {\n \n  return (\n    <div>\n      <h1>search in server component</h1>\n      <SearchBar/>\n    </div>\n  )\n}\n

Conclusion

Mastering server components and search parameters is crucial for modern web development. By leveraging the power of React and Next.js, developers can create highly performant and interactive applications. Whether you're implementing search functionality or filtering data on the server, understanding these concepts will enable you to build more efficient and user-friendly web applications.

Share

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policyTerms & Conditions