skip to Main Content

I’m trying to create a SignUp authentication page with firebase, So when I’m try to type anything in the textfield every time the text field got reset, I cant able to find the problem. But the main problem I found that with the "onChange" property. Please fix the issue why the textfield state change every time.
The SignUp page code:

import React,{useState,useContext} from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { styled } from '@mui/material';
import Logo from '../assets/QpiVolta-Logo.png'
import { useTheme,IconButton } from '@mui/material';
import { tokens } from '../theme';
import {Person,Lock, Mail, Visibility, VisibilityOff} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { UserAuth } from '../context/AuthContext';

const SignUp = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  
  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => setShowPassword((show) => !show);

  const handleMouseDownPassword = (event) => {
    event.preventDefault();
  };

  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [name,setName] = useState("")
  const [error, setError] = useState("")
  const {signUp} = UserAuth()
  const navigate = useNavigate()
  const handleSubmit= async(e) => {
    e.preventDefault()
    try {
      await signUp(email,password)
      setError('')
      navigate('/') 
    }
    catch (error) {
      console.log(error)
      setError(error.message)
    }
  }
    const RootStyle = styled("div")({
        backgroundColor:"#d4cbf6",
        background:`${colors.primary[400]} !important`,
        height: "100vh",
        display: "flex",
        placeItems: "center",
    });
    const logoStyle = {
      height: '80px',
      
    };

    const CssTextField = styled(TextField)({
      '& label.Mui-focused': {
        color: `${colors.pinkAccent[500]}`,
      },
      '& .MuiInput-underline:after': {
        borderBottomColor:  `${colors.pinkAccent[500]}`,
      },
      '& .MuiOutlinedInput-root': {
        '& fieldset': {
          borderColor: 'grey',
        },
        '&:hover fieldset': {
          borderColor: `${colors.pinkAccent[500]}`,
        },
        '&.Mui-focused fieldset': {
          borderColor: `${colors.pinkAccent[500]}`,
        },
      },
    });
    return (
      <RootStyle>
        <Container  maxWidth="sm" >
        <Box
          sx={{
            marginTop: 8,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',            
          }}
        >
          
          <img component="img" src={Logo} style={logoStyle}  />
          <Typography component="h1" variant="h2" color={colors.grey[100]} >
            Create an account<span style={{ color:`${colors.pinkAccent[500]}`}}>.</span>
          </Typography>
          <Box component="form"  onSubmit={handleSubmit} sx={{ mt: 2 , mb:2}}>
            <Grid container spacing={3} >
              <Grid item xs={12} sm={6} >
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Person sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
              <CssTextField  
                  fullWidth
                  label="First Name" 
                  id="FirstName"
                  name="FirstName"
                  autoComplete="family-name"
                  variant='standard' 
                  value={name}
                  onChange={(e)=> setName(e.target.value)}
              />
                  </Box>
              </Grid>
              <Grid item xs={12} sm={6}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Person sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                  fullWidth
                  id="lastName"
                  label="Last Name"
                  name="lastName"
                  autoComplete="family-name"
                  variant='standard' 
                />
                </Box>
              </Grid>
              <Grid item xs={12}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Mail sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                  required
                  fullWidth
                  id="email"
                  label="Email Address"
                  name="email"
                  value={email}
                  autoComplete="email"
                  variant='standard' 
                  onChange={(e) => {
                    console.log(e.target.value); // add this line
                    setEmail(e.target.value);
                  }}
                />
                </Box>
              </Grid>
              <Grid item xs={12}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Lock sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                   required
                   fullWidth
                   name="password"
                   label="Password"
                   id="password"
                   autoComplete="new-password"
                   type={showPassword ? 'text' : 'password'}
                   variant='standard'
                   value={password}
                   onChange={(e) => setPassword(e.target.value)}
                   InputProps={{
                     endAdornment: (
                      <IconButton
                        aria-label="toggle password visibility"
                        onClick={handleClickShowPassword}
                        onMouseDown={handleMouseDownPassword}
                      >
                        {showPassword ? <Visibility /> : <VisibilityOff />}
                      </IconButton>
                     ),
                   }}
                />
                </Box>
              </Grid>
            </Grid>
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
            >
              Sign Up
            </Button>
            <Grid container justifyContent="flex-end">
              <Grid item>
                <Link href="/Login" variant="body2" sx={{color:"grey"}}>
                  Already have an account? Sign in
                </Link>
              </Grid>
            </Grid>
          </Box>
        </Box>
      </Container>
      </RootStyle>    
  )
  }
  
  export default SignUp

2

Answers


  1. You should not put CssTextField and RootStyled components inside SignUp component. Put it outside and it works

    import TextField, { TextFieldProps } from '@mui/material/TextField';
    
    type StyledTextFieldProps = TextFieldProps & {
        colors?: any,
    };
    const CssTextField =
        styled(TextField, {
            shouldForwardProp: (prop) => prop !== 'colors',
        }) <
        StyledTextFieldProps >
        ((props) => ({
            '& label.Mui-focused': {
                color: `${props.colors.pinkAccent[500]}`,
            },
            '& .MuiInput-underline:after': {
                borderBottomColor: `${props.colors.pinkAccent[500]}`,
            },
            '& .MuiOutlinedInput-root': {
                '& fieldset': {
                    borderColor: 'grey',
                },
                '&:hover fieldset': {
                    borderColor: `${props.colors.pinkAccent[500]}`,
                },
                '&.Mui-focused fieldset': {
                    borderColor: `${props.colors.pinkAccent[500]}`,
                },
            },
        }));
    
    const RootStyle = styled('div')((props) => ({
        backgroundColor: '#d4cbf6',
        background: `${props.colors.primary[400]} !important`,
        height: '100vh',
        display: 'flex',
        placeItems: 'center',
    }));
    
    const SignUp = () => {
        const colors = tokens(theme.palette.mode);
    
        return (
            <RootStyle colors={colors}>
                <CssTextField
                    fullWidth
                    label="First Name"
                    id="FirstName"
                    name="FirstName"
                    autoComplete="family-name"
                    variant="standard"
                    colors={colors}
                    onChange={(e) => setName(e.target.value)}
                />
            </RootStyle>
        );
    };
    
    Login or Signup to reply.
  2. Try adding value prop as well for each text field. Something like below

    <CssTextField  
                      fullWidth
                      label="First Name" 
                      id="FirstName"
                      name="FirstName"
                      autoComplete="family-name"
                      variant='standard' 
                      onChange={(e)=> setName(e.target.value)}
                      value={name}
                  />
    

    do this for other text field as well where onChange prop is present.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search