Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
SuccessFollower Avatar asked Nov 06 '22 04:11

SuccessFollower


1 Answers

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.

like image 60
Matthew Brooks Avatar answered Nov 12 '22 13:11

Matthew Brooks