Reputation: 1
I am trying to set the default value of Textfield in the react material-ui. It is working without the material-ui Textfield. But when I am using the Textfield it is not working. Ex. Working with "input" but not with "TextField".
I want to use it for form editing purpose. Please help me to find out the solution. Thank you in advance. Below is the code for the example.
import React,{useEffect,useState } from "react";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
const submit = values => {
console.log(values);
};
const initialValues = {
name: '',
};
const Editform = () => {
const [uname, setname] = useState('');
useEffect(() => {
setname("Jubed Alam"); //it should be default value. But not reflecting
});
return (
<form>
<TextField
margin="normal"
label="Name"
fullWidth
name="name"
defaultValue={uname}
/>
<Button variant="contained" color="primary" type="submit">
Submit
</Button>
</form>
);
}
export default Editform;
Upvotes: 0
Views: 1806
Reputation: 145
i ran into same issue it fixed for me when I used multiline
<TextField
required
id="receiverName"
label="Receiver Name"
defaultValue={addressArray[0]}
fullWidth
multiline
onChange={(e) => setRcvName(e.target.value)}
/>;
Upvotes: 2
Reputation: 474
you don't need to update its default value in useEffect(). and use value instead of defaultValue, just do it like this:
const Editform = () => {
const [uname, setname] = useState("Jubed Alam");
return (
<form>
<TextField
margin="normal"
label="Name"
fullWidth
name="name"
value={uname}
onChange={(e)=> setname(e.target.value)}
/>
<Button variant="contained" color="primary" type="submit">
Submit
</Button>
</form>
);
}
Upvotes: 1