SuccessFollower
SuccessFollower

Reputation: 220

How to build a custom material-ui component

I have to customize the TextField component to build a time duration compomnent.

enter image description here

enter image description here

Any help would be appreciated.

Upvotes: 5

Views: 1637

Answers (2)

Ivan Satsiuk
Ivan Satsiuk

Reputation: 353

IMO you don't need to create a custom MUI component, you can use what the library provides already.

for date/time picker MUI suggests to use material-ui-pickers library

Upvotes: 0

Matthew Brooks
Matthew Brooks

Reputation: 571

I don't think it's in the spirit of SO to simply provide you with an implementation, so I'm going to try to help break this down and point you in the direction of the docs that should help you and an approach that could work for you.

This looks like you'll need to compose some lower-level MUI components together. Take a look at the MUI TextField docs on customization and you can see an example of using InputBase, which you'll likely need.

Another point here is that any TextField component from MUI is going to provide you with a single value for change events. It looks like what you have here is a compound value.

function DurationField({ value, onChange }) {
  // For example, you could model the value for this field to be an array of two values.
  const [hours, minutes] = value
  return (
    // instead of div, you may need FormControl and FormControlLabel, etc.
    <div>
      <InputBase value={hours} onChange={(e) => {
        onChange([e.target.value, minutes])
      }} />
      <InputBase value={minutes} onChange={(e) => {
        onChange([hours, e.target.value])
      }} />
    </div>
  )
}

You're also going to have to think about what the focus states are going to look like. How does a user use their keyboard to navigate into, through, and out of this input? What do the styles look like for those?

But from here, you should take a look at FormControl etc., all of the lower-level components you can find at the bottom of the TextField doc page I linked to. By using those, carefully overriding styles where needed, and thoughtfully crafting the value/onChange props, you should be able to make a nice component that works well within the MUI world.

Upvotes: 1

Related Questions