Created
August 31, 2019 20:23
-
-
Save macndesign/e184b18e21dd45b9b53de858cd7026d2 to your computer and use it in GitHub Desktop.
react functional component (validate with refs)
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 { TextField } from '@material-ui/core'; | |
function App() { | |
const [value, setValue] = useState(''); | |
const handleChange = event => { | |
setValue(event.target.value); | |
}; | |
return ( | |
<div> | |
<MyTextField value={value} | |
handleChange={handleChange} /> | |
</div> | |
); | |
} | |
function MyTextField({value, handleChange, ...props}) { | |
const ref = createRef(); | |
const [qty, setQty] = useState(0); | |
useEffect(() => { | |
setQty(ref.current.value.length); | |
}, [value]); | |
return ( | |
<div> | |
<TextField inputRef={ref} | |
value={value} {...props} | |
onChange={handleChange} /> | |
{qty > 5 && <div>Error</div>} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment