Categories
React Answers

How to style a React Material UI text field?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *