I have a form that has a few textfields in it. If you have a certain role then you should be able to click in the fields and type but if you do not have the admin role then they should all be disabled. How would I disable all the textfields given this situation? Here is my code. I am fairly new to react and any help would be appreciated.
I could do something like this but is there an easier way with less repetition as this form is most definitely to get bigger and more complex and I should be able to disable the entire thing if not given the correct role.
export default function BasicTextFields() {
const classes = useStyles();
const hasRole = authService.verifyRole(role.admin)
return (
{hasRole ? (
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Title" />
<TextField id="filled-basic" label="Description" />
<TextField id="outlined-basic" label="Data" variant="outlined" />
</form>
);
) : (
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Title" disabled/>
<TextField id="filled-basic" label="Description" disabled/>
<TextField id="outlined-basic" label="Data" variant="outlined" disabled/>
</form>
}
CodePudding user response:
Rather than duplicating your elements and passing disabled
as a single keyword (which is a shorthand for disabled={true}
, you can explicitly pass a boolean value to it:
export default function BasicTextFields() {
const classes = useStyles();
const hasRole = authService.verifyRole(role.admin)
return (
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Title" disabled={!hasRole}/>
<TextField id="filled-basic" label="Description" disabled={!hasRole}/>
<TextField id="outlined-basic" label="Data" variant="outlined" disabled={!hasRole}/>
</form>
);
}
CodePudding user response:
Little simpler...
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Title" disabled={!hasRole}/>
<TextField id="filled-basic" label="Description" disabled={!hasRole} />
<TextField id="outlined-basic" label="Data" variant="outlined" disabled={!hasRole}/>
</form>