Conditional Rendering Inside A Function

a125 :

I have seen multiple examples but none of them fit my problem. I want to use conditional rendering inside a functional component. For example, if the user is not logged in and a token is not present in the local storage, when the login form is submitted, I want to display a message that login is invalid.

if (!localStorage.getItem('token'))
  {
    return <Typography>Login Invalid</Typography>
    console.log('Login Not possible');
  }

For now, I tried to make it a separate function and called it in onSubmit() of my form. But there's no output for that.

function ShowError(){
  if (!localStorage.getItem('token'))
  {
    return <Typography>Login Invalid</Typography>
  }
  else{
    console.log('Login Done');
  }
}
        return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
          <Container component="main" maxWidth="xs">
            <CssBaseline />
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center'
            }}>
              <Formik
                initialValues={{ email: '', password: '' }}
                onSubmit={(values, actions) => {
                  setTimeout(() => {
                    alert(JSON.stringify(values, null, 2));
                    actions.setSubmitting(false);
                  }, 1000);
                }}
                validationSchema={schema}
              >
                {props => {
                  const {
                    values: { email, password },
                    errors,
                    touched,
                    handleChange,
                    isValid,
                    setFieldTouched
                  } = props;
                  const change = (name: string, e: any) => {
                    e.persist();                
                    handleChange(e);
                    setFieldTouched(name, true, false);
                    setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
                  };
                  return (
                    <form style={{ width: '100%' }} 
                    onSubmit={e => {e.preventDefault();
                    submitForm(LoginMutation); ShowError()}}>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="email"
                        fullWidth
                        name="email"
                        helperText={touched.email ? errors.email : ""}
                        error={touched.email && Boolean(errors.email)}
                        label="Email"     
                        value={email}
                        onChange={change.bind(null, "email")}
                      />
                      <TextField
                        variant="outlined"
                        margin="normal"
                        fullWidth
                        id="password"
                        name="password"
                        helperText={touched.password ? errors.password : ""}
                        error={touched.password && Boolean(errors.password)}
                        label="Password"
                        type="password"
                        value={password}
                        onChange={change.bind(null, "password")}
                      />
                      <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                      />
                      <br />
                      <Button className='button-center'
                        type="submit"
                        disabled={!isValid || !email || !password}
                        onClick={handleOpen}
                        style={{
                          background: '#6c74cc',
                          borderRadius: 3,
                          border: 0,
                          color: 'white',
                          height: 48,
                          padding: '0 30px'
                        }}
                      >

                        Submit</Button>
                      <br></br>
                      <Grid container>
                        <Grid item xs>
                          <Link href="#" variant="body2">
                            Forgot password?
                    </Link>
                        </Grid>
                        <Grid item>
                          <Link href="#" variant="body2">
                            {"Don't have an account? Sign Up"}
                          </Link>
                        </Grid>
                      </Grid>
                      {/* <Snackbar open={open} autoHideDuration={6000} >
        <Alert severity="success">
          This is a success message!
        </Alert>
      </Snackbar> */}
                    </form>
                  )
                }}
              </Formik>
            </div>
            <Box mt={8}>
              <Copyright />
            </Box>
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

f I do this {localStorage.getItem('token') && <Typography>Invalid Login</Typography>}

it will be rendered even before the form is submitted but I only want it to appear if the form is not submitted. How can I fix this?

deowk :

You could use a ternary statement instead of if/else

function isLoggedIn(){
  return typeof localStorage.getItem('token') !== 'undefined'
}

...

const isLoggedIn = isLoggedIn()
const [formSubmitted, setSubmit] = useState(false)
const [loggedIn, setLoggedIn] = useState(isLoggedIn)

useEffect(() => {
  if (loggedIn) {
   localStorage.set('token', [token])
  }
}, [loggedIn])

return (
  <Mutation mutation={LoginMutation}>
    {(LoginMutation: any) => (
      ...
      <Grid container>
        <Grid item xs>
          <Link href="#" variant="body2">
            Forgot password?
          </Link>
        </Grid>
        <Grid item>
          <Link href="#" variant="body2">
            {"Don't have an account? Sign Up"}
          </Link>
        </Grid>
        {!loggedIn && formSubmitted  ? <Typography>Login Invalid</Typography> : null}
      </Grid>
      ...
    )}
  </Mutation>
);

export default LoginPage;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31702&siteId=1