Skip to content

Instantly share code, notes, and snippets.

@heerdyes
Last active September 7, 2023 05:07
Show Gist options
  • Save heerdyes/b62fd139c1bf59f13af7633376caa5a7 to your computer and use it in GitHub Desktop.
Save heerdyes/b62fd139c1bf59f13af7633376caa5a7 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
import './App.css';
function App() {
const [skey, setSkey] = useState('');
const [links, setLinks] = useState([]);
return (
<div>
<h1>hello react</h1>
<SearchBox srchkey={skey} setSrchkey={setSkey} setLinks={setLinks}></SearchBox>
<hr />
<ResultBox srchkey={skey} links={links}></ResultBox>
</div>
);
}
function SearchBox({ srchkey, setSrchkey, setLinks }) {
const [srchtext, setSrchtext] = useState('');
function handleSearch(e) {
setSrchtext(e.target.value);
}
function performSearch() {
console.log(srchtext);
setSrchkey(srchtext);
// call backend
fetch('http://localhost:3000/search')
.then(r => r.json())
.then(data => {
console.log(data);
setLinks(data);
});
}
return (
<div>
<input onChange={handleSearch} value={srchtext}></input>
<button onClick={performSearch}>Go</button>
</div>
);
}
function ResultBox({ srchkey, links }) {
return (
<ul>
{links
.filter(m => m.link.includes(srchkey))
.map(m =>
<li key={m.id}>
<a tabIndex={0} href={m.link}>{m.desc}</a>
</li>)}
</ul>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment