Created
October 6, 2019 16:39
-
-
Save prrraveen/44db6f671663bfe5575f6fbf4218171d 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
import React, { Component } from 'react' | |
class App extends React.Component { | |
state = { | |
text: 'Peter' | |
} | |
divRef = React.createRef() | |
handleChange = (e) => { | |
const text = e.target.value | |
this.setState({ text }) | |
} | |
getGender = () => { | |
const { text } = this.state | |
const _this = this | |
fetch(`https://api.genderize.io?name=${text}`) | |
.then(function(response) { | |
return response.text(); | |
}) | |
.then((text) => { | |
console.log('gender is', JSON.parse(text)) | |
const result = JSON.parse(text) | |
const gender = result.gender || 'not found' | |
this.divRef.current.innerText = `Result: ${gender.toUpperCase()}` | |
}) | |
.catch(function(error) { | |
console.log('request failed', error) | |
}) | |
} | |
reset = () => { | |
this.setState({ text: '', }) | |
this.divRef.current.innerText = `` | |
} | |
render() { | |
const { text } = this.state | |
return ( | |
<div className="App"> | |
<input value={text} onChange={this.handleChange} placeholder="enter name"/> | |
<button onClick={this.getGender}>Get Gender</button> | |
<button onClick={this.reset}>Reset</button> | |
<div ref={this.divRef} /> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment