Created
August 17, 2017 18:41
-
-
Save Temzasse/2e2f7e0a55c971f48b20a1c1bb87f4a7 to your computer and use it in GitHub Desktop.
TextField with floating label (no styles)
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
const propTypes = { | |
label: PropTypes.string, | |
value: PropTypes.string.isRequired, | |
onChange: PropTypes.func.isRequired, | |
}; | |
class TextField extends Component { | |
state = { | |
isFocused: false, | |
} | |
handleFocus = () => { | |
this.setState({ isFocused: true }); | |
}; | |
handleBlur = () => { | |
this.setState({ isFocused: false }); | |
}; | |
handleLabelClick = () => { | |
const { isFocused } = this.state; | |
const { value } = this.props; | |
if (!isFocused && !value) { | |
this.setState({ isFocused }); | |
this._input.focus(); | |
} | |
}; | |
render() { | |
const { label, value, ...rest } = this.props; | |
const { isFocused } = this.state; | |
return ( | |
<TextFieldWrapper> | |
{label && | |
<Label | |
up={isFocused || value} | |
onClick={this.handleLabelClick} | |
> | |
{label} | |
</Label> | |
} | |
<Input | |
value={value} | |
onChange={this.props.onChange} | |
onFocus={this.handleFocus} | |
onBlur={this.handleBlur} | |
innerRef={node => { this._input = node; }} | |
{...rest} | |
/> | |
</TextFieldWrapper> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment