简体   繁体   中英

Is it possible to use conditional inside a react component?

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>
                )}
            />

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM