简体   繁体   中英

How to set a HTML element ID on a material-ui component?

I have a website built with Gatsby.js using the Material-UI .

Specific problem is this: I want to use the Google Tag Manager "Element Visibility" triggers. If some HTML element becomes visible, GTM should fire some GA tag.

Question is this: how can I specify the HTML ID for a material-ui component for GTM (or anything else) to find it?

First example:

// ...react imports omitted...
import makeStyles from '@material-ui/core/styles/makeStyles';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import CloseIcon from '@material-ui/icons/Close';

import Link from '~components/Link';
import ButtonSubmit from '~components/form-buttons/ButtonSubmit';
import Container from '~components/Container';

// ... all other imports are in-house code

const useStyles = makeStyles(theme => ({ /* ...styles... */}));

const GuestUserSoftSaleSecondPopup = ({ which, ...rest }) => {
  const classes = useStyles();

  // ...setup code omitted...

  return (
    <Box bgcolor="#474d5c" width="100%" py={4} className={classes.banner}>
      <Container>
        <Grid container direction="row" justify="space-between" alignItems="center" spacing={2}>
          <Grid item xs={12} sm={1} md={3} lg={4}>
            <CloseIcon onClick={handleClose} size="large" className={classes.closeIcon} />
          </Grid>

          <Grid item xs={12} sm={7} md={5} lg={4}>
            <Link to="/subscribe" variant="h5" className={classes.linkStyle}>
              Become a member for full access
            </Link>
          </Grid>
          <Grid item xs={12} sm={4} className={classes.buttonPosition}>
            <Link to="/subscribe" underline="none" className={classes.linkStyle}>
              <ButtonSubmit type="button" fullWidth={false}>
                See my option
              </ButtonSubmit>
            </Link>
          </Grid>
        </Grid>
      </Container>
    </Box>
  );
};
// ...proptypes and `export` clause

Second example:

// ...react imports omitted...
import makeStyles from '@material-ui/core/styles/makeStyles';
import MuiDialog from '@material-ui/core/Dialog';

const useStyles = makeStyles(() => ({ /* ...styles... */ }));

const Dialog = ({ children, background, backdrop, isOpen, ...rest }) => {
  const classes = useStyles({ background });
  return (
    <MuiDialog
      open={isOpen}
      maxWidth="sm"
      fullWidth
      disableBackdropClick
      disableEscapeKeyDown
      BackdropProps={{
        className: backdrop ? classes.backdropBM : classes.backdrop
      }}
      PaperProps={{
        className: classes.paper
      }}
      scroll="body"
      {...rest}
    >
      {children}
    </MuiDialog>
  );
};

If you look at the API documentation for almost any of the Material-UI components, you will find at the end of the "Props" section a statement like the following example from Dialog :

Any other props supplied will be provided to the root element (Modal).

This means that any props not explicitly recognized by this component will be passed along eventually to whatever HTML element is the outermost element rendered. So for most Material-UI components, in order to add an id property, you just specify it.

My example below (a modification of the Simple Dialog demo ) includes three different ids: one on the Dialog element which will be placed on the outermost div of the Modal , one specified via the PaperProps which will go on the main Paper div of the visible content of the dialog, and one on the Box wrapped around the dialog content.

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Avatar from "@material-ui/core/Avatar";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import ListItemText from "@material-ui/core/ListItemText";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import PersonIcon from "@material-ui/icons/Person";
import Typography from "@material-ui/core/Typography";
import { blue } from "@material-ui/core/colors";
import Box from "@material-ui/core/Box";

const emails = ["username@gmail.com", "user02@gmail.com"];
const useStyles = makeStyles({
  avatar: {
    backgroundColor: blue[100],
    color: blue[600]
  }
});

function SimpleDialog(props) {
  const classes = useStyles();
  const { onClose, selectedValue, open } = props;

  const handleClose = () => {
    onClose(selectedValue);
  };

  const handleListItemClick = value => {
    onClose(value);
  };

  return (
    <Dialog
      onClose={handleClose}
      aria-labelledby="simple-dialog-title"
      open={open}
      PaperProps={{ id: "MyDialogPaperID" }}
      id="ThisIDWillBeOnTheModal"
    >
      <DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
      <Box id="MyBoxID">
        <List>
          {emails.map(email => (
            <ListItem
              button
              onClick={() => handleListItemClick(email)}
              key={email}
            >
              <ListItemAvatar>
                <Avatar className={classes.avatar}>
                  <PersonIcon />
                </Avatar>
              </ListItemAvatar>
              <ListItemText primary={email} />
            </ListItem>
          ))}
        </List>
      </Box>
    </Dialog>
  );
}

SimpleDialog.propTypes = {
  onClose: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired,
  selectedValue: PropTypes.string.isRequired
};

export default function SimpleDialogDemo() {
  const [open, setOpen] = React.useState(false);
  const [selectedValue, setSelectedValue] = React.useState(emails[1]);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = value => {
    setOpen(false);
    setSelectedValue(value);
  };

  return (
    <div>
      <Typography variant="subtitle1">Selected: {selectedValue}</Typography>
      <br />
      <Button variant="outlined" color="primary" onClick={handleClickOpen}>
        Open simple dialog
      </Button>
      <SimpleDialog
        selectedValue={selectedValue}
        open={open}
        onClose={handleClose}
      />
    </div>
  );
}

在对话框、纸张和框上编辑 id

Material UI components don't let you set an id for them since the implementation inside should be a black box and may contain multiple html element. See if you can wrap the element in a div and put the id on that instead.

Another option would be to add a class (via the classes prop) to the element instead but I'm not sure if Google Tag Manager can use those instead of ids.

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