reactjstypescriptmaterial-uireact-propshigh-order-component

React, Material-UI: How to composition functional component with customized props using typescript


I'm trying to make MyCustomButton compositioning with Button in Material-ui

import React from "react";
import { Button, ButtonProps } from "@material-ui/core";

interface MyButtonProps {
  'aria-label': string, // I'd like to add a aria-label as required property
  myOptionalProperty?: string
}

export default function MyButton(buttonProps: ButtonProps, myButtonProps: MyButtonProps) {
  return (
    <Button {...buttonProps, ...myButtonProps} />
  );
}

And I've got an error code following: Parsing error: expression expected.

I've get some information via official documents in material-ui, but I haven't done composition.

full code is in https://codesandbox.io/s/jolly-dawn-keuj5

Does anyone give me some solution?

Thank you for your time.


Solution

  • Guessing you don't need to pass two props to <Button />

    import React from "react";
    import { Button, ButtonProps } from "@material-ui/core";
    
    interface MyButtonProps {
      title: string,
      myOptionalProperty?: string
    }
    
    export default function MyButton<P extends ButtonProps>(myButtonProps: MyButtonProps) {
      return (
        <Button {...myButtonProps as P} />
      );
    }
    

    Try it online:

    Edit adoring-haibt-8xrfe


    Info me if this doesn't fit your demand or I missed something important