Skip to content

Instantly share code, notes, and snippets.

@prrraveen
Created October 6, 2019 16:39
Show Gist options
  • Save prrraveen/44db6f671663bfe5575f6fbf4218171d to your computer and use it in GitHub Desktop.
Save prrraveen/44db6f671663bfe5575f6fbf4218171d to your computer and use it in GitHub Desktop.
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