Skip to content Skip to sidebar Skip to footer

Conditional Rendering Inside A Function

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 to

Solution 1:

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;

Solution 2:

Why not simply insert a condition before your final return. I usually do this to show some error.

Let's say your component is called LoginPage. Then -

function LoginPage() {
 ...//do something



...//do something

  if (!localStorage.getItem('token'))
  {
    return <Typography>Login Invalid</Typography>
  }

  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)}}>
                      <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>
                        **IF ELSE STATEMENT HERE**
                      </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;

Solution 3:

function renderMe(){
  if (!localStorage.getItem('token'))
  {
    return <ErrorComponent />
  }else{
    return <Dashboard />
  }
}
return renderMe();

this worked for me just fine. i hope this fixes your probleme.


Post a Comment for "Conditional Rendering Inside A Function"