Skip to content

Instantly share code, notes, and snippets.

@luciovilla
Last active November 18, 2021 23:13
Show Gist options
  • Save luciovilla/54ae3b4f3825b8ca5136117e4be44427 to your computer and use it in GitHub Desktop.
Save luciovilla/54ae3b4f3825b8ca5136117e4be44427 to your computer and use it in GitHub Desktop.
import { useRef } from 'react';
import { useRouter } from 'next/router';
export default function SearchComponent() {
const searchInputRef = useRef(null);
const router = useRouter();
const search = (event) => {
event.preventDefault();
const term = searchInputRef.current.value;
router.push(`/search?q=${term}`);
}
return (
<form>
<input ref={searchInputRef} type="text"/>
<button onClick={(event)=>search(event)}> Search </button>
</form>
)
}
import { useRouter } from 'next/router';
export default function Search({ results }) {
const router = useRouter();
return (
<div className="border-t border-black pt-4 mx-8">
<h3 className="uppercase text-m pb-4">{router.query.term}</h3>
<ul className="last:border-b-0">
{results.map((entry) => {
if (!entry) {
return null;
}
return (
<li>
<div>
<Link href={`/entry/${entry.uid}`}>
<a className="hover:text-pink-500 cursor-pointer font-semibold text-lg leading-3">
{entry.title}
</a>
</Link>
</div>
<div className="w-1/4">
{entry.leadImage?.variantUrl && aspectRatio !== null && (
<Image
src={entry.leadImage.variantUrl}
width={WIDTH}
height={Math.floor(WIDTH / aspectRatio)}
layout="responsive"
/>
)}
</div>
</li>
);
})}
</ul>
</div>
)
}
export async function getServerSideProps(context) {
const startIndex = context.query.start || '0';
const data = await fetch(`https://www.googleapis.com/customsearch/v1?key=${process.env.GOOGLE_API_KEY}&cx=${process.env.CONTEXT_KEY}&q=${context.query.term}&start=${startIndex}`).then(res => res.json()).catch(error => {
console.error(error)
});
return {
props: {
results: data ? data : null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment