Created
July 1, 2020 18:50
-
-
Save 3on/2f136cfb5cb8724f67519939cd9312ea to your computer and use it in GitHub Desktop.
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
| /* | |
| https://cataas.com/cat/says/te | |
| */ | |
| class CatSearch extends React.Component { | |
| constructor(props) { | |
| super(props) | |
| this.state = { | |
| search: '', | |
| searches: [] | |
| } | |
| } | |
| handleOnChange = (evt) => { | |
| const val = evt.target.value; | |
| this.setState({search: val}); | |
| this.fetch(val); | |
| }; | |
| fetch (text) { | |
| const {searches} = this.state; | |
| const url = `https://cataas.com/cat/says/${text}`; | |
| const preload = new Image(); | |
| preload.src = url; | |
| preload.onload = this.handleLoaded(text); | |
| this.setState({searches: [...searches, {url, text, loaded: false}]}); | |
| } | |
| handleLoaded = (text) => () => { | |
| const {searches} = this.state; | |
| this.setState({searches: searches.map(s => (s.text === text)? {...s, loaded: true} : s)}); | |
| } | |
| render() { | |
| const { search, searches} = this.state; | |
| const img = []; | |
| searches.forEach(s => { | |
| if (!s.loaded) { | |
| return; | |
| } | |
| img.unshift( | |
| <li key={s.text}> | |
| <img src={s.url} alt={s.text}/> | |
| </li>) | |
| }); | |
| return ( | |
| <div className="catdex"> | |
| <input placeholder="Type to load a cat" value={search} onChange={this.handleOnChange} /> | |
| <ul> | |
| {img} | |
| </ul> | |
| </div> | |
| ) | |
| } | |
| } | |
| ReactDOM.render(<CatSearch />, document.querySelector("#app")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment