Categories
React Answers

How to style a React Material UI text field?

Sometimes, we want to style a React Material UI text field.

In this article, we’ll look at how to style a React Material UI text field.

How to style a React Material UI text field?

To style a React Material UI text field, we can call the makeStyles function with a function that returns an object that specifies the styles.

Then we can set the InputProps prop of the TextField to specify the styles of the input element in the text field.

And we can specify the styles for the rest of the text field with the className prop of the TextField.

For instance, we write:

import { makeStyles, TextField } from "@material-ui/core";
import React, { useState } from "react";

const useStyles = makeStyles(() => ({
  textField: {
    width: "90%",
    marginLeft: "auto",
    marginRight: "auto",
    paddingBottom: 0,
    marginTop: 0,
    fontWeight: 500
  },
  input: {
    color: "white"
  }
}));

export default function App() {
  const classes = useStyles();
  const [email, setEmail] = useState();

  return (
    <div>
      <TextField
        id="email"
        label="Email"
        className={classes.textField}
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        margin="normal"
        InputProps={{
          className: classes.input
        }}
      />
    </div>
  );
}

We call makeStyles with a function that returns an object that has properties that are used as class names.

And we set the class name properties to objects with styles that we want to apply.

Next, we set the className prop to the classes.textField class to style the TextField‘s styles to apply the styles in the textField object property returned by the callback we passed into makeStyles.

And we set the InputProps prop to an object that has the className property set to classes.input to apply the styles in the input style object property.

Conclusion

To style a React Material UI text field, we can call the makeStyles function with a function that returns an object that specifies the styles.

Then we can set the InputProps prop of the TextField to specify the styles of the input element in the text field.

And we can specify the styles for the rest of the text field with the className prop of the TextField.

Categories
React Answers

How to apply styles for CSS pseudo selectors with Material UI?

Sometimes, we want to apply styles for CSS pseudo selectors with Material UI.

In this article, we’ll look at how to apply styles for CSS pseudo selectors with Material UI.

How to apply styles for CSS pseudo selectors with Material UI?

To apply styles for CSS pseudo selectors with Material UI, we can add style properties for pseudoselectors.

For instance, we write:

import { makeStyles } from "@material-ui/core";
import React from "react";

const useStyles = makeStyles(() => ({
  paragraphWithWarningDiv: {
    margin: "32px 0px 24px",
    "& :nth-child(1)": {
      marginBottom: "100px"
    }
  }
}));

export default function App() {
  const classes = useStyles();

  return (
    <div className={classes.paragraphWithWarningDiv}>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
    </div>
  );
}

We call makesStyles with an object to apply extra bottom margin to the first child element of the parent with class paragraphWithWarningDiv.

We set the marginBottom of the first child element by setting the "& :nth-child(1)" property to an object with marginBottom set to '100px'.

As a result, we see that the first p element has a 100px bottom margin.

Conclusion

To apply styles for CSS pseudo selectors with Material UI, we can add style properties for pseudoselectors.

Categories
React Answers

How to get data from the React Material UI TextField component?

Sometimes, we want to get data from the React Material UI TextField component.

In this article, we’ll look at how to get data from the React Material UI TextField component.

How to get data from the React Material UI TextField component?

To get data from the React Material UI TextField component, we can get the input value from the onChange function.

In the function, we can get the input value from the e.target.value property and set that as the value of a state.

For instance, we write:

import { TextField } from "material-ui";
import React, { useState } from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";

export default function App() {
  const [value, setValue] = useState("");

  return (
    <MuiThemeProvider>
      <div>
        <TextField
          value={value}
          onChange={(e) => {
            setValue(e.target.value);
          }}
        />
      </div>
    </MuiThemeProvider>
  );
}

We set onChange to a function that calls setValue with e.target.value to set the value state to the input value.

Then we set the value prop of the TextField to the value state show the input value in the text field.

Conclusion

To get data from the React Material UI TextField component, we can get the input value from the onChange function.

In the function, we can get the input value from the e.target.value property and set that as the value of a state.

Categories
React Answers

How to pass props to React Material UI styles?

Sometimes, we want to pass props to React Material UI styles.

In this article, we’ll look at how to pass props to React Material UI styles.

How to pass props to React Material UI styles?

To pass props to React Material UI styles, we can call the useStyle hook returned by makeStyles with the props object.

In makeStyles, we can set the style properties that takes the props as a parameter and return the value we want.

For instance, we write:

import React from "react";
import { makeStyles } from "@material-ui/core";

const useStyles = makeStyles({
  firstStyle: {
    backgroundColor: (props) => props.backgroundColor
  },
  secondStyle: {
    color: (props) => props.color
  }
});

const MyComponent = ({ children, ...props }) => {
  const { firstStyle, secondStyle } = useStyles(props);
  return <div className={`${firstStyle} ${secondStyle}`}>{children}</div>;
};

export default function App() {
  return (
    <MyComponent color="yellow" backgroundColor="purple">
      hello world
    </MyComponent>
  );
}

We call makeStyles with an object that has some class names as properties.

And we set the properties to objects with style properties set to functions that returns the prop value we want.

Next, we define the MyComponent component that gets the props and pass it into useStyles.

Then we set the className to the classes that are returned from useStyles.

Finally, we render MyComponent with color and backgroundColor to render the colors that we set.

They will end up as values in the object that we pass into makeStyles.

As a result, the box has a purple background and the color of the text is yellow.

Conclusion

To pass props to React Material UI styles, we can call the useStyle hook returned by makeStyles with the props object.

In makeStyles, we can set the style properties that takes the props as a parameter and return the value we want.

Categories
React Answers

How to make a dropdown menu open below the Appbar using React Material-UI?

Sometimes, we want to make a dropdown menu open below the Appbar using React Material-UI.

In this article, we’ll look at how to make a dropdown menu open below the Appbar using React Material-UI.

How to make a dropdown menu open below the Appbar using React Material-UI?

To make a dropdown menu open below the Appbar using React Material-UI, we set the Menu‘s getContentAnchorEl to null.

Then we set anchorOrigin and transformOrigin to objects to position the menu.

For instance, we write:

import React from "react";
import { alpha, makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import Typography from "@material-ui/core/Typography";
import Badge from "@material-ui/core/Badge";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import MenuIcon from "@material-ui/icons/Menu";
import AccountCircle from "@material-ui/icons/AccountCircle";
import MailIcon from "@material-ui/icons/Mail";
import NotificationsIcon from "@material-ui/icons/Notifications";
import MoreIcon from "@material-ui/icons/MoreVert";

const useStyles = makeStyles((theme) => ({
  grow: {
    flexGrow: 1
  },
  menuButton: {
    marginRight: theme.spacing(2)
  },
  title: {
    display: "none",
    [theme.breakpoints.up("sm")]: {
      display: "block"
    }
  },
  search: {
    position: "relative",
    borderRadius: theme.shape.borderRadius,
    backgroundColor: alpha(theme.palette.common.white, 0.15),
    "&:hover": {
      backgroundColor: alpha(theme.palette.common.white, 0.25)
    },
    marginRight: theme.spacing(2),
    marginLeft: 0,
    width: "100%",
    [theme.breakpoints.up("sm")]: {
      marginLeft: theme.spacing(3),
      width: "auto"
    }
  },
  searchIcon: {
    padding: theme.spacing(0, 2),
    height: "100%",
    position: "absolute",
    pointerEvents: "none",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  },
  inputRoot: {
    color: "inherit"
  },
  inputInput: {
    padding: theme.spacing(1, 1, 1, 0),
    // vertical padding + font size from searchIcon
    paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
    transition: theme.transitions.create("width"),
    width: "100%",
    [theme.breakpoints.up("md")]: {
      width: "20ch"
    }
  },
  sectionDesktop: {
    display: "none",
    [theme.breakpoints.up("md")]: {
      display: "flex"
    }
  },
  sectionMobile: {
    display: "flex",
    [theme.breakpoints.up("md")]: {
      display: "none"
    }
  }
}));

export default function App() {
  const classes = useStyles();
  const [, setAnchorEl] = React.useState(null);
  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null);

  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

  const handleProfileMenuOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMobileMenuClose = () => {
    setMobileMoreAnchorEl(null);
  };

  const handleMobileMenuOpen = (event) => {
    setMobileMoreAnchorEl(event.currentTarget);
  };

  const mobileMenuId = "primary-search-account-menu-mobile";
  const renderMobileMenu = (
    <Menu
      anchorEl={mobileMoreAnchorEl}
      id={mobileMenuId}
      keepMounted
      open={isMobileMenuOpen}
      onClose={handleMobileMenuClose}
      getContentAnchorEl={null}
      anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      transformOrigin={{ vertical: "top", horizontal: "center" }}
    >
      <MenuItem>
        <IconButton color="inherit">
          <Badge badgeContent={4} color="secondary">
            <MailIcon />
          </Badge>
        </IconButton>
        <p>Messages</p>
      </MenuItem>
      <MenuItem>
        <IconButton color="inherit">
          <Badge badgeContent={11} color="secondary">
            <NotificationsIcon />
          </Badge>
        </IconButton>
        <p>Notifications</p>
      </MenuItem>
      <MenuItem onClick={handleProfileMenuOpen}>
        <IconButton color="inherit">
          <AccountCircle />
        </IconButton>
        <p>Profile</p>
      </MenuItem>
    </Menu>
  );

  return (
    <div className={classes.grow}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start"
            className={classes.menuButton}
            color="inherit"
            aria-label="open drawer"
          >
            <MenuIcon />
          </IconButton>
          <Typography className={classes.title} variant="h6" noWrap>
            Material-UI
          </Typography>
          <div className={classes.grow} />
          <div className={classes.sectionMobile}>
            <IconButton onClick={handleMobileMenuOpen} color="inherit">
              <MoreIcon />
            </IconButton>
          </div>
        </Toolbar>
      </AppBar>
      {renderMobileMenu}
    </div>
  );
}

We call makeStyles to add some styles for the menu.

Then we call the useStyles hook which is returned by makeStyles to return the classes object.

Next, we define states and functions for handling the opening and closing of the menu.

To make the top right menu open below the app bar, we set getContentAnchorEl to null.

Then we set anchorOrigin to an object with the vertical property set to 'bottom' and horizontal set to 'center'.

And we set transformOrigin to an object that has the vertical property set to 'top' and horizontal set to 'center'

We assign the Menu component to renderMobileMenu and put it below AppBar.

Conclusion

To make a dropdown menu open below the Appbar using React Material-UI, we set the Menu‘s getContentAnchorEl to null.

Then we set anchorOrigin and transformOrigin to objects to position the menu.