Skip to content

Instantly share code, notes, and snippets.

@dfoverdx
Created November 13, 2018 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfoverdx/8850cf866d9cb81d96139268eaf8f8bb to your computer and use it in GitHub Desktop.
Save dfoverdx/8850cf866d9cb81d96139268eaf8f8bb to your computer and use it in GitHub Desktop.
Reactstrap Input that doesn't validate or invalidate until the element has been touched
import React, { PureComponent } from 'react';
import { Input } from 'reactstrap';
/**
* A wrapper for reactstrap's Input which prevents the `invalid` and `valid` props from being displayed until the user
* has touched the input (via `onBlur`). Also handles setting `invalid` if it is not defined as a property, but
* other HTML5 input validation properties are (`pattern`, `required`, `min`, etc).
*/
export default class TouchedInput extends PureComponent {
constructor(props) {
super(props);
this.state = {
touched: false
};
this.inputRef = React.createRef();
}
trigger() {
this.setState({
touched: true
});
}
render() {
let {
invalid,
valid,
onBlur: deferredOnBlur,
...props
} = this.props,
{ touched } = this.state,
onBlur = (...args) => {
this.setState({ touched: true });
deferredOnBlur && deferredOnBlur(...args);
};
if (invalid === undefined && this.inputRef.current) {
invalid = !this.inputRef.current.validity.valid;
}
return <Input {...props} innerRef={this.inputRef} valid={touched && !props.disabled && valid}
invalid={touched && !props.disabled && invalid} onBlur={onBlur} />;
}
static propTypes = {
/** Inherits all the properties from reactstrap's `Input` component, which itself inherits all the properties of
* HTMLInputElement. */
...Input.propTypes,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment