Skip to content

Instantly share code, notes, and snippets.

@macndesign
Created August 31, 2019 20:56
Show Gist options
  • Save macndesign/02977d0c03c47225e097a411130f8a8b to your computer and use it in GitHub Desktop.
Save macndesign/02977d0c03c47225e097a411130f8a8b to your computer and use it in GitHub Desktop.
refs validation using material ui
import React, { createRef, useEffect, useState }
from 'react';
import { FormControl, InputLabel, FormHelperText, Input }
from '@material-ui/core';
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>
);
}
const MyTextField = ({value, handleChange}) => {
const ref = createRef();
const [qty, setQty] = useState(0);
const classes = useStyles();
useEffect(() => {
setQty(ref.current.value.length);
}, [ref]);
const hasError = qty > 5;
return (
<FormControl className={classes.formControl} error={hasError}>
<InputLabel htmlFor="component-error">Name</InputLabel>
<Input
id="component-error"
value={value}
onChange={handleChange}
aria-describedby="component-error-text"
inputRef={ref}
/>
{
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