JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Customizing MUI: TextField

--

Photo by Motiur Rahman Shakil on Unsplash

Being a front-end web developer, I have to constantly deal with creating high-quality user interfaces with proper functioning to provide a clean and enjoyable user experience.

People think Front End Developer’s work is to only create the “website”. Maybe these are the ones who consider HTML a programming language🤷

More pragmatically, we don’t have websites now, we have “web apps” and web apps are not just about the “design” there is a great emphasis on the functioning part.

I have most of my work in React JS. If you have worked with React you must be aware of Material UI or MUI. It is a great library that provides well-written, consistent, functional, customizable, and well-designed React components that are very easy to integrate.

In this article, I will be showing you how I made a custom TextField component that can be used for Dates. Dates are just an example but with this template in mind, you can easily extend this to other fields like email, phone number, etc.

All this is ok, but WHY?

Well, Good Question!

Most of the time you can get away without caring too much about customizing MUI components but let’s say the TextField is being used in many places for different purposes then you have to get onto the rough track of customization.

I was working on a project that had specific form fields like GST, PAN, etc. which require their validations and some different stylings, and since they were scattered across the application it makes sense to make a common component that I can use in all places.

<TextField/> of MUI is a very capable component and I have leveraged this component and adjusted it to my needs.

Talk is Cheap, show me the code!

Alright, let’s get to it:

Create a component named DateField

import { TextField } from "@mui/material";
import React from "react";

const DateField = (props) =>
return (
<TextField
label={"HELLO THERE}
type="date"
/>
);
};

export default DateField;

<TextField/> in this code is pretty basic, let’s spice things up. For this, we will use props.

const DateField = ({
date,
handleDateChange,
dateError,
disabled = false,
required = true,
label = "Select a suitable day",
sx
}) =>
return (
<TextField
label={label}
type="date"
InputLabelProps={{ shrink: true, required: true }}
inputProps={{
style: { textTransform: "uppercase" },
}}
sx={sx}
value={date}
required={required}
disabled={disabled}
onChange={handleDateChange}
error={dateError}
helperText={dateError ? "Select a valid date" : ""}
/>
);
};

export default DateField;

Let’s look at the props once:

  • date: The variable that stores the current date value, generally a useState().
  • handleDateChange: This function is responsible for updating the value of the date state.
  • dateError: This is also a state that handles whether the Date field has any error or not
  • sx: This is a concept from MUI that allows us to work with a superset of CSS. We can use this to pass on inline styling to our component if required.

Now, you can declare all the required variables where you want to call the <DateField/>, and then you have to pass them as props.

import { useState } from "react";
import DateField from "./DateField";

export default function App() {
const [date, setDate] = useState(new Date());
const [dateError, setDateError] = useState(false);
const handleDateChange = (e) => {
setDate(e.target.value);
};

return (
<DateField
date={date}
handleDateChange={handleDateChange}
dateError={dateError}
label="Select a Day"
/>
);
}

Well, this is sufficient enough to be used but we can add up more functionality in this component to make it even more functional.

We will add a method in the component to restrict the user from selecting a date that has passed, in other words, the user can not select a past date.

Inside the DateField component, we can add a function that handles the logic for past dates and we can control this behavior using a prop.

const hidePastDate = () => {
const today = new Date();
const dd = String(today.getDate() + 1).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
return yyyy + "-" + mm + "-" + dd;
};
const DateField = ({
date,
handleDateChange,
dateError,
disabled = false,
required = true,
disablePastDate = true,
label = "Select a suitable day",
sx
}) => {
const hidePastDate = () => {
const today = new Date();
const dd = String(today.getDate() + 1).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
return yyyy + "-" + mm + "-" + dd;
};
return (
<TextField
label={label}
type="date"
InputLabelProps={{ shrink: true, required: true }}
inputProps={{
style: { textTransform: "uppercase" },
min: disablePastDate && hidePastDate()
}}
sx={sx}
value={date}
required={required}
disabled={disabled}
onChange={handleDateChange}
error={dateError}
helperText={dateError ? "Select a valid date" : ""}
/>
);
};

export default DateField;

This is the complete component. Here we have used a prop disablePastDate to control whether we want to allow the user to enter a past date or not.

This is just an example of how we can do this, but similarly, we can make a function that can restrict the user from selecting a future date. It mostly depends on your use case to allow for functionality.

It is easier to get overwhelmed by adding more and more functionalities into a component, but that is not ideal. You have to understand the requirement and then add up the required functionality only.

I hope this article was worth your time, I will be covering more such topics in the Future😁

In Plain English

Thank you for being a part of our community! Before you go:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

No responses yet

Write a response