Last active
October 2, 2023 08:58
-
-
Save hansamlin/3615e4ef33c1c1418f7242a8757a2ddf to your computer and use it in GitHub Desktop.
Google custom search by react.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#search { | |
margin: auto; | |
} | |
#search-container { | |
width: 500px; | |
height: 300px; | |
margin: auto; | |
} | |
#googlesearch form{ | |
display: none; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
import "./search.css"; | |
const Search = () => { | |
const [value, setValue] = useState(""); | |
useEffect(() => { | |
(function () { | |
const cx = "abc:123"; | |
const gcse = document.createElement("script"); | |
gcse.type = "text/javascript"; | |
gcse.async = true; | |
gcse.src = `https://cse.google.com/cse.js?cx=${cx}`; | |
const s = document.getElementsByTagName("script")[0]; | |
s.parentNode.insertBefore(gcse, s); | |
})(); | |
var renderSearchForms = function () { | |
if (document.readyState === "complete") { | |
window.google.search.cse.element.render({ | |
div: "googlesearch", | |
tag: "search", | |
gname: "gsearch", | |
}); | |
} else { | |
window.google.setOnLoadCallback(function () { | |
window.google.search.cse.element.render({ | |
div: "googlesearch", | |
tag: "search", | |
gname: "gsearch", | |
}); | |
}, true); | |
} | |
}; | |
window.__gcse = { | |
parsetags: "explicit", | |
callback: renderSearchForms, | |
}; | |
}, []); | |
useEffect(() => { | |
const input = document.getElementById("search"); | |
const submit = (e) => { | |
if (e.keyCode === 13) { | |
const element = window.google.search.cse.element.getElement("gsearch"); | |
element.execute(value); | |
} | |
}; | |
input.addEventListener("keyup", submit); | |
return () => input.removeEventListener("keyup", submit); | |
}, [value]); | |
const handleChange = (e) => { | |
setValue(e.target.value); | |
}; | |
const handleClick = () => { | |
if (value.lenght > 0) { | |
const element = window.google.search.cse.element.getElement("gsearch"); | |
element.execute(value); | |
} | |
}; | |
return ( | |
<div id="search-container"> | |
<input name="search" id="search" value={value} onChange={handleChange} /> | |
<button id="submit" onClick={handleClick}> | |
送出 | |
</button> | |
<div id="googlesearch"></div> | |
</div> | |
); | |
}; | |
export default Search; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment