Skip to content

Instantly share code, notes, and snippets.

@macndesign
Created August 31, 2019 20:23
Show Gist options
  • Save macndesign/e184b18e21dd45b9b53de858cd7026d2 to your computer and use it in GitHub Desktop.
Save macndesign/e184b18e21dd45b9b53de858cd7026d2 to your computer and use it in GitHub Desktop.
react functional component (validate with refs)
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