Created
August 31, 2019 20:56
-
-
Save macndesign/02977d0c03c47225e097a411130f8a8b to your computer and use it in GitHub Desktop.
refs validation using material ui
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
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