How to create onSubmit with Material-UI
The class property/ styles shouldn't have any effect on form submission custom function. If you think that ditching the 'class props' you can get a custom function to work - post your code so we can help you further. [Your code is missing submit function]
Here is one way to add custom submit function
const Login = (props) => {
const {classes} = props;
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log( 'Email:', email, 'Password: ', password);
// You should see email and password in console.
// ..code to submit form to backend here...
}
return( <div >
<Paper className={classes.root}>
<form className={classes.container} onSubmit={handleSubmit} >
<TextField
....
value={email}
onInput={ e=>setEmail(e.target.value)}
.....
/>
<TextField
....
value={password}
onInput={ e=>setPassword(e.target.value)}
....
/>
<Typography className={classes.divider} />
<Button
type="submit"
....
className={classes.button}
>
Login
</Button>
</form>
</Paper>
</div>
);
Glanyx
Updated on June 09, 2020Comments
-
Glanyx almost 4 years
So I'm fairly new to node.js / react / material-ui. I've been following a guide to try setting up a website and have been getting on pretty well. I decided to include material-ui for snazzy components (not part of the guide) and then got stuck because I can't seem to fire custom functions whilst using a themed ui.
With the below code, I can create everything fine if I ditch the 'classes' props. I can add my function and everything works. But I obviously lose all my styling if I do this.
const styles = theme => ({ // Styling - omitted }); const Login = (props) => { const {classes} = props; return( <div> <Paper className={classes.root}> <form className={classes.container} noValidate autoComplete="off"> <TextField id="email" label="Email" className={classes.textField} InputProps={{ className: classes.input }} type="email" name="email" autoComplete="email" margin="normal" variant="outlined" required autoFocus /> <TextField id="outlined" label="Password" className={classes.textField} InputProps={{ className: classes.input }} type="password" autoComplete="current-password" margin="normal" variant="outlined" required /> <Typography className={classes.divider} /> <Button type="submit" variant="contained" color="inherit" className={classes.button} > Login </Button> </form> </Paper> </div> ); } Login.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Login);
I'm trying to combine the styling as well as being able to fire a custom function to submit the form data. Does anyone have any thoughts?
-
Glanyx almost 5 yearsHeck sweet. I didn't quite know where to start, but this should get me going. I'll give this a try later on, thank you!