Skip to content

Instantly share code, notes, and snippets.

@lirenyeo
Last active October 9, 2018 16:02
Show Gist options
  • Save lirenyeo/ae28742ad3ce0e6a1209f34931017956 to your computer and use it in GitHub Desktop.
Save lirenyeo/ae28742ad3ce0e6a1209f34931017956 to your computer and use it in GitHub Desktop.
import React from 'react'
class App extends React.Component {
state = {
input: '', // The actual typed text
hasImage: false, // The checkbox state to indicate whether there is an image
}
handleInput = e => {
// Uncheck image whenever typed text length is 15 or less, else it remains in the original state
// A perhaps more readable code would be:
/*
if (this.state.input.length < 16) {
this.setState({input: e.target.value, hasImage: false})
} else {
this.setState({input. e.target.value})
}
*/
// or a more unreadable code:
/*
this.setState({
input: e.target.value,
...this.state.input.length < 16 && { hasImage: false}
})
*/
this.setState({
input: e.target.value,
hasImage: this.state.input.length < 16 ? false : this.state.hasImage,
})
}
handleToggle = e => this.setState({ hasImage: e.target.checked })
render() {
// Javascript destructuring, so that the return() code is more readable
const { input, hasImage } = this.state
const { length } = input
// actualLength considers image. Image weights 15 chars
const actualLength = hasImage ? length + 15 : length
return (
<div>
<div>Remaining char: { actualLength }</div>
<input
type="text"
value={ input }
onChange={ this.handleInput }
/>
<button disabled={ actualLength === 0 || actualLength > 135 }>
Tweet
</button>
<div>
<input
type="checkbox"
checked={ hasImage }
onChange={ this.handleToggle }
disabled={ length < 15 || length > 120 }
/>
Insert Image
</div>
</div>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment