Search code examples
reactjsbuttoncomponentsmaterial-uireusability

How to reuse a Custom Material-ui button inside a react-app?


I'm developing my first React app. I've imported a Material-ui button and I've customized it.

Now I want to reuse this custom button in several components of my app. I want a different text for each time I use this custom button.

Where do I need to write this specific text for each button?

My button is visible when I import it in other components, but I can't see the text I wrote inside the button component. The button stays empty.

My custom button component : MyButton:

import React from "react";
import Button from "@material-ui/core/Button";
import { withStyles } from "@material-ui/core/styles";

const styles = () => ({
  button: {
    margin: 50,
    padding: 10,
    width: 180,
    fontSize: 20
  }
});

function MyButton(props) {
  const { classes } = props;
  return (
    <Button variant="contained" color="primary" className={classes.button}>
      <b>  </b>
    </Button>
  );
}

export default withStyles(styles)(MyButton);

The other component where I import MyButton component : Home :

import React from "react";
import "../App.css";
import MyButton from "./Button";

function Header() {
  return (
    <header className="Header">
      {/* background image in css file */}
      <h1>Welcome </h1>
      <h3> description...</h3>
      <MyButton>Play now</MyButton>
    </header>
  );
}

export default Header;

I expect the button to show "Play now" (expected output) but for now it stays empty (actual output).


Solution

  • Also, I've found another solution that offers the possibility to write directly the text inside each button (children of MyButton), and customize it if needed.

    Pass "children" keyword as "props" to MyButton component :

    function MyButton(props) {
      const { classes, children } = props;
      return (
        <Button variant="contained" color="primary" className={classes.button}>
          <b>{children}</b>
        </Button>
      );
    }
    

    Then write the text of your button inside the button as you will do in html :

    <MyButton> Play now </MyButton>