Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a correct way to extend Material-UI components (React / Typescript)

I'm trying to extend material-ui components as my own component with custom properties. I'm using reactjs w/ typescript.

The below code is my trial :

import React from 'react';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core';
import { Theme } from '@material-ui/core/styles/createMuiTheme';
import Tabs, { TabsProps } from '@material-ui/core/Tabs';

export interface Iprops extends TabsProps {
  /* how to add a variant ? */
}

const useStyles = makeStyles((theme: Theme) => ({
    root: {
       // styles
     }
}));

export const BasicTabs = (props: Iprops) => {
    const classes = useStyles(props);
    if (props.variant === 'test') {
        return (
            <Tabs
                {...props}
                className={clsx(classes.root, props.className)}
            />
        );
    }
    return (
        <Tabs {...props} />
    );
};

So, what Im trying to do now is return a custom styled button when the variant is 'test'.

So, my first question is
1. How to add a new variant to the button?

the second question is
2. should I pass the children like

<Tabs {...props}>{props.children}</Tabs>

all the time whenever I extend a material-ui components?

like image 866
doobean Avatar asked Oct 16 '25 13:10

doobean


1 Answers

import React from 'react'
import TextField, { StandardTextFieldProps } from '@material-ui/core/TextField'

/**
 * Extend properties
 */
export interface PasswordProps extends StandardTextFieldProps {
    custom: string
}

/**
 * Password input
 * @param props Properties
 */
export const PasswordField: React.FunctionComponent<PasswordProps> = (props) => {
    props = Object.assign({ type: 'password' }, props)
    return (
        <TextField {...props}>
            {props.children}
        </TextField>
    )
}

For your questions: A. Extend the props, add variants to the interface you want. B. Yes, always like this as suggested with React official 'composition model' https://reactjs.org/docs/composition-vs-inheritance.html

like image 63
Garry Xiao Avatar answered Oct 18 '25 07:10

Garry Xiao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!