Home > Blockchain >  Specifying class for properties and styles for components and tags in React
Specifying class for properties and styles for components and tags in React

Time:12-14

I am pretty new to React. I was actually building an AppBar with a logo at center based on a suggestion in this enter image description here

Tried the way @Dimitriy suggested and below my code

export default function AppBar({ open, onDrawerOpen }:any) {
    const theme = useTheme();
    const iconButtonOptions = {
        color: "inherit",
        ariaLabel: "open drawer",
        onClick: onDrawerOpen,
        edge: "start",
        sx: {{ mr: 2, ...(open && { display: "none" }) }}
      }
    return (
        <AppBar position="fixed" style={{ background: "#002a5e" }} open={open}>
        <Toolbar>
            <Box sx={{ display: "flex",flexDirection:"row", alignItems: "center", flex: "1" }}>
            <IconButton {...iconButtonOptions} >
                <MenuIcon />
            </IconButton>
            <Typography variant="h6" noWrap component="div">
                TITLE
            </Typography>
            </Box>
            <Box
            component="img"
            sx={{
                height: 32,
            }}
            alt="MyLogo"
            src={logo}
            />
            <Box sx={{ flex: "1" }}></Box>
        </Toolbar>
        </AppBar>
    );
  }

But its saying

Cannot redeclare block-scoped variable '(Missing)'.ts(2451)

enter image description here

CodePudding user response:

Yes, there's actually is the way for that.

First, you can make a new object variable that will hold all of your props. Example:

const iconBtnProps = {
   color: 'inherit',
   aria-label: 'open drawer',
   onClick: onDrawerOpen,
   edge: 'start',
   sx: { mr: 2, ...(open && { display: "none" }) }
};

// render the <IconButton /> component and spread the object
<IconButton {...iconBtnProps} />

CodePudding user response:

I would advise you to check styled-components. It would really make things easier for styling components.

CodePudding user response:

You can't define jsx component props through classes. But if you want to make your jsx more understandable, or avoid repetition, you can move all the props into an object.

const iconButtonOptions = {
  color: "inherit",
  ariaLabel: "open drawer",
  onClick: onDrawerOpen,
  edge: "start",
  sx: { mr: 2, ...(open && { display: "none" }) }
}

return (
  <IconButton {...iconButtonOptions}>
    <MenuIcon />
  </IconButton>
)
  • Related