0

First of all, my excuses if I'm not expressing myself correctly, I'm still a bit confused with Typescript.

I have a styled button from Material-UI and I'm not sure how to proceed with making this button reusable throughout the whole app. I basically would like the button to receive a prop such as {buttonText} or so, so I can just use it in multiple pages but with different labels.

import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';

const useStyles = makeStyles({
  backButton: {
    background: 'linear-gradient(45deg, #9AA5B0 30%, #9AA5B0 90%)',
    border: 0,
    borderRadius: 25,
    boxShadow: '0 2px 4px rgba(0, 0, 0, .5)',
    color: 'white',
    fontFamily: 'Poppins, sans-serif',
    fontSize: 15,
    height: 37,
    padding: '0 20px',
    textTransform: 'none',
  },
});

export default function BackButton(): React.ReactElement {
  const classes = useStyles();
  return (
    <Button className={classes.backButton} startIcon={<ChevronLeftIcon />}>
      {buttonText}
    </Button>
  );
}

So when I insert the button component in another page, I could just give a value to the props and then the right label would show on my button.

<div>
  <PrimaryButton />
  <BackButton label={buttonText}/>
</div>

Any suggestions on how to make this work, using types?

Many thanks in advance!

1 Answer 1

2

First, your component BackButton need to accept props.

Then you make a type to props:

export type BackButtonProps = {
  label: string;
};

And add to your BackButton Component:

export type BackButtonProps = {
  label: string; // or buttonText
  // ...other props
};

export default function BackButton(props: BackButtonProps) {
  const classes = useStyles();
  return (
    <Button className={classes.backButton} startIcon={<ChevronLeftIcon />}>
      {props.label}
    </Button>
  );
}

Now, your BackButton has props which has a type.

Using:

<BackButton label="Custom Label" />

If the library has an internal type to his button, you can extends this type, so your type will have all properties by inheritance:

import { AnyExistingType } from 'material-ui';

export type BackButtonProps = AnyExistingType & { label: string };

Sign up to request clarification or add additional context in comments.

1 Comment

Not all heroes wear capes. THANK YOU! I finally understand how the types work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.