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
functionisLoggedIn(){
returntypeoflocalStorage.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 (
<Mutationmutation={LoginMutation}>
{(LoginMutation: any) => (
...
<Gridcontainer><Griditemxs><Linkhref="#"variant="body2">
Forgot password?
</Link></Grid><Griditem><Linkhref="#"variant="body2">
{"Don't have an account? Sign Up"}
</Link></Grid>
{!loggedIn && formSubmitted ? <Typography>Login Invalid</Typography> : null}
</Grid>
...
)}
</Mutation>
);
exportdefaultLoginPage;
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 -
functionLoginPage() {
...//do something
...//do somethingif (!localStorage.getItem('token'))
{
return<Typography>Login Invalid</Typography>
}
return(
<Mutationmutation={LoginMutation}>
{(LoginMutation: any) => (
<Containercomponent="main"maxWidth="xs"><CssBaseline /><divstyle={{display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}><FormikinitialValues={{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 (
<formstyle={{width: '100%' }}
onSubmit={e => {e.preventDefault();
submitForm(LoginMutation)}}>
<TextFieldvariant="outlined"margin="normal"id="email"fullWidthname="email"helperText={touched.email ? errors.email: ""}
error={touched.email && Boolean(errors.email)}
label="Email"value={email}onChange={change.bind(null, "email")}
/><TextFieldvariant="outlined"margin="normal"fullWidthid="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")}
/><FormControlLabelcontrol={<Checkboxvalue="remember"color="primary" />}
label="Remember me"
/>
<br /><ButtonclassName='button-center'type="submit"disabled={!isValid || !email || !password}
onClick={handleOpen}style={{background: '#6c74cc',
borderRadius:3,
border:0,
color: 'white',
height:48,
padding: '030px'
}}
>
Submit</Button><br></br><Gridcontainer><Griditemxs><Linkhref="#"variant="body2">
Forgot password?
</Link></Grid><Griditem><Linkhref="#"variant="body2">
{"Don't have an account? Sign Up"}
</Link></Grid>
**IF ELSE STATEMENT HERE**
</Grid>
{/* <Snackbaropen={open}autoHideDuration={6000} ><Alertseverity="success">
This is a success message!
</Alert></Snackbar> */}
</form>
)
}}
</Formik></div><Boxmt={8}><Copyright /></Box></Container>
)
}
</Mutation>
)
}
exportdefaultLoginPage;
Solution 3:
functionrenderMe(){
if (!localStorage.getItem('token'))
{
return<ErrorComponent />
}else{
return<Dashboard />
}
}
returnrenderMe();
this worked for me just fine. i hope this fixes your probleme.
Post a Comment for "Conditional Rendering Inside A Function"