I am trying to implement conditional rendering in react using ternary operator, but I can't seem to get the syntax right. Here's what I have below:
const [isDeleted, setIsDeleted] = useState(false);
I have a function which deletes users:
const deleteUser = () => {
axios.post("http://localhost:5000/delete", []).then((resp) => {
setIsDeleted(resp.data);
isDeleted(true);
});
};
I am calling the deleteUser
function onclick below, which changes isDeleted
to true.
<Box>
<Button
sx={{
padding: "10px 20px",
}}
onClick={deleteUser}
>
Delete User
</Button>
</Box>
Below, want to use ternary operation here to render successfully deleted
if isdeleted is true, and display Hello User
if it isdeleted is false. What I have is just priniting it on my screen. I can't seem to get the right syntax.
<Typography
fontWeight="bold"
>
isDeleted? Successfully Deleted : Hello User
</Typography>
CodePudding user response:
Wrap the statement with {}
{ isDeleted ? <>Successfully Deleted</> : <>Hello User</>}
CodePudding user response:
Missing brackets
<Typography fontWeight="bold">
{isDeleted? "Successfully Deleted" : "Hello User"}
</Typography>
CodePudding user response:
Try the following:
<Typography fontWeight="bold">
{isDeleted ? `Successfully Deleted` : `Hello User`}
</Typography>
CodePudding user response:
Ternary is JavaScript expression. All such expressions should be enclosed inside brackets {}
:
<Typography fontWeight="bold">
{isDeleted ? "Successfully Deleted" : "Hello User"}
</Typography>
CodePudding user response:
you are setting your response data in setIsDeleted(resp.data);
and isDeleted is object not function so you need to setIsDeleted(true)