I want to get input data from the user when they click submit form button. When clicked, i'm getting a response object with null values shown in the screenshot. From what I understand, I don't want useState because it'll make the page do a re-render, and I don't want that. This is my first time with useRef, is there something i'm missing?
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { useRef } from "react";
const ContactSection = () => {
let nameRef = useRef(null); // name
let emailRef = useRef(null); // email
let messageRef = useRef(null); // message
const formSubmit = (event) => {
event.preventDefault();
const data = {
name: nameRef.current.value,
email: emailRef.current.value,
message: messageRef.current.value,
};
console.log(data);
};
return (
<Box component="form">
<TextField
ref={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
<Button
variant="contained"
onClick={formSubmit}
sx={{
mt: 4,
"&:hover": {
color: "secondary.main",
transition: "ease-in 0.2s",
transform: "scale(1.05)",
},
}}
>
Submit
</Button>
);
};
export default ContactSection;
I'm getting this error in the console when trigger formSubmit handle
CodePudding user response:
When using MUI TextField change the ref to inputRef
<Box component="form">
<TextField
inputRef={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
This will give the correct output in the console log
CodePudding user response:
You have to use inputRef
instead of ref
for more information refer to the official doc. https://mui.com/api/text-field/
CodePudding user response:
Use inputRef instead of ref for material UI text field component . Reference : https://mui.com/components/text-fields/#main-content