Home > Software design >  Is it possible to use conditional inside a react component?
Is it possible to use conditional inside a react component?

Time:06-10

Im using Material UI and CardHeader is a component (the top part of a post). I want to render 2 button on the post if the post (isUser = true )is posted by the user. Is that possible?

            <CardHeader
                avatar={
                    <Avatar sx={{ bgcolor: "red" }} aria-label="recipe">
                        U
                    </Avatar>
                }

                title={username}
                
                {isUser && (
                    <Box display="flex">
                        <IconButton onClick={handleEdit} sx={{ marginLeft: "auto" }}>
                            <EditIcon />
                        </IconButton>
                        <IconButton onClick={handleDelete}>
                            <DeleteForeverIcon />
                        </IconButton>
                    </Box>
                )}
            />

CodePudding user response:

Assuming you want those buttons to appear in the card header's action area, you just need to assign them to the action prop...

<CardHeader
  avatar={
    <Avatar sx={{ bgcolor: "red" }} aria-label="recipe">
      U
    </Avatar>
  }
  title={username}
  action={
    isUser && (
      <Box display="flex">
        <IconButton onClick={handleEdit} sx={{ marginLeft: "auto" }}>
          <EditIcon />
        </IconButton>
        <IconButton onClick={handleDelete}>
          <DeleteForeverIcon />
        </IconButton>
      </Box>
    )
  }
/>;

For more details on the component's available props, see the documentation.

  • Related