Skip to content

Instantly share code, notes, and snippets.

@macndesign
Created August 31, 2019 21:14
Show Gist options
  • Save macndesign/f7216e8068605cc2a03b4efb4791da3a to your computer and use it in GitHub Desktop.
Save macndesign/f7216e8068605cc2a03b4efb4791da3a to your computer and use it in GitHub Desktop.
react functional component refs validation
import React, { createRef, useEffect, useState }
from 'react';
import PropTypes from 'prop-types';
import { FormControl, InputLabel, FormHelperText, Input }
from '@material-ui/core';
import MaskedInput from 'react-text-mask';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
formControl: {
margin: theme.spacing(1),
},
}));
const App = () => {
const [value, setValue] = useState('');
const handleChange = event => {
setValue(event.target.value);
};
return (
<div>
<MyTextField value={value}
handleChange={handleChange} />
</div>
);
}
function TextMaskCustom(props) {
const { inputRef, ...other } = props;
return (
<MaskedInput
{...other}
ref={ref => {
inputRef(ref ? ref.inputElement : null);
}}
mask={['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
placeholderChar={'\u2000'}
/>
);
}
TextMaskCustom.propTypes = {
inputRef: PropTypes.func.isRequired,
};
const MyTextField = ({value, handleChange}) => {
const ref = createRef();
const [qty, setQty] = useState(0);
const classes = useStyles();
useEffect(() => {
const valueNumbers = onlyNumbers(ref.current.value);
setQty(valueNumbers.length);
}, [ref]);
const onlyNumbers = value => value.match(/[0-9]/gi) || [];
const hasError = qty > 0 && qty < 10;
return (
<FormControl className={classes.formControl} error={hasError}>
<InputLabel htmlFor="component-error">Celular</InputLabel>
<Input
id="component-error"
value={value}
onChange={handleChange}
aria-describedby="component-error-text"
inputRef={ref}
inputComponent={TextMaskCustom}
/>
{
hasError &&
<FormHelperText id="component-error-text">
Error</FormHelperText>
}
</FormControl>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment