Search code examples
javascriptreactjsecmascript-6material-uitextinput

why does the input field state is not changing while typing in textField MUI


In my react.js component, when i am trying to start type anything in textField, it is not updating .

I tried with debugger the i found -- when first character entered, component re-renderd so looses its prevous states and looks like textField value is not updating.

It was working fine earlier when i was using mui Box instead of Grid, but now removing Grid also is not working . Same question asked by many people, i went through their provided solution but no luck.

Here is my code :

const Registration = (props: any) => {       

            const [loading, setLoading] = useState(false);
            const [successAlert, setSuccessAlert]=useState(false)
            const [formData, setFormData] = useState({
            firstName:'',
            })
           const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
               event.preventDefault();
               submitRegister()
             };
           
            const submitRegister = async()=>{
             setLoading(true)
             axios.post('example.com/create/user',formData)
             .then(response =>{
               console.log(response.data.code)
               if(response.data.code ===200){
                 setSuccessAlert(true)
                 setLoading(false)
               }
             })
             .catch(error =>{
               console.log(error)
           
             })
           
            }  

            const handleChangeForm=(e:ChangeEvent<HTMLInputElement>)=>{
             const{name ,value }= e.target;
             setFormData((prevFormData)=>({
               ...prevFormData,
               [name]:value
             }));
           };

           const FormContainer = styled("form")(({ theme }) => ({
            maxWidth: 700,
            [theme.breakpoints.down(theme.breakpoints.values.sm)]: {
              maxWidth: 300
            },
            [theme.breakpoints.up(theme.breakpoints.values.md)]: {
              maxWidth: 650
            }
          }));

          const StyledTextField = styled(TextField)(() => ({
            "& .MuiFormLabel-asterisk": {
              color: "red"
            },
            '& label.Mui-focused': {
              color: '#96A8AE', //Dark Grey as per SCM
          },
          '& .MuiOutlinedInput-root': {
              '&.Mui-focused fieldset': {
                  borderColor: '#96A8AE',
              },
          },
          
          }));
               
               return (
                       <Grid container className="registration__container" spacing={2}>
                           <Grid item xs={7} md={7} lg={7} xl={7}>
                             <Grid className='left'>
                               
                               // some code here
                             </Grid>
                             {loading &&<Loader /> }
                           </Grid>
                           <Grid item xs={5} md={5} lg={5} xl={5} className='registration__form' key="regis-form">
                               
                               <FormContainer onSubmit={handleSubmit}>
                                   <Grid item container className='details__form' columnSpacing={{ xs: 2, sm: 2, md: 2 }}>
                                       <Grid item xs={6} md={6} lg={6} xl={6}>
                                           <StyledTextField
                                               label="First Name"
                                               name="firstname"
                                               value={formData.firstName}
                                               onChange={handleChangeForm}
                                               key="firstName"                                    
                                               size='medium'
                                               required
                                               fullWidth
                                             />
                                       </Grid>
                                     </Grid>
               
                                   
                                   <Grid item xs={12} className="submitbtn__wrapper">
                                         <button type="submit">Register</button>
                                   </Grid>
               
                                 </FormContainer>
                           </Grid>
                     </Grid>
                 );
       };
       
       export default Registration;

I also Tried- React.js - input losing focus when rerendering

React Hooks - Input loses focus when 1 character is typed in

In React ES6, why does the input field lose focus after typing a character? and other similar question , but did not help me.


Solution

  • I think you are passing name prop in TextField incorrectly.

    For example:

    <StyledTextField
      label="First Name"
      name="firstName"   // this line (you are using "firstname")
      value="{formData.firstName}"
      onChange="{handleChangeForm}"
      key="firstName"
      size="medium"
      required
      fullWidth
    />
    

    And in your code, you need to move StyledTextField and FormContainer outside of the component to avoid causing unnecessary re-rendering.

    For example:

    const FormContainer = styled("form")(({ theme }) => ({
      /* ... */
    }));
    
    const StyledTextField = styled(TextField)(() => ({
      /* ... */
    }));
    
    const Registration = (props: any) => {
      /* ... */
    };
    
    export default Registration;