jazzfaz
jazzfaz

Reputation: 183

Passing props not working Material UI react

I was trying to pass a prop to modify the button style. In this case, I'd like the button to be "blue" and backgroundColor "orange".

I passed a cool="true" in when calling Button, but the button is still "red" in "yellow", as if the cool state is false..

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

/* This is an example of passing props */
const useStyles = makeStyles({
  buttonStyle: (props) => {
    return {
      color: props.cool ? "blue" : "red",
      backgroundColor: props.cool ? "orange" : "yellow",
    };
  },
});

function App(props) {
  const classes = useStyles(props);
  console.log(classes);
  return (
    <>
      <Button cool="true" className={classes.buttonStyle}>
        Click me!
      </Button>
    </>
  );
}

export default App;

thanks for the answers. Below fixes the problem. I was wondering if it is possible to include the "cool" modifier in the <Button ..> so that it is easier to read, since return () has many parts besides button.

function App() {
  const classes = useStyles({ cool: true });
  console.log(classes);
  return (
    <>
      <h1 className={classes.textStyle}>Let's roll this app out.</h1>
      <Button className={classes.buttonStyle}>Click me!</Button>
    </>
  );
}

Upvotes: 0

Views: 1310

Answers (3)

Yushan
Yushan

Reputation: 1047

If you want to update the styles of the button using component props, then create a separate component that changes the button styles according to the props.

CoolButton.jsx

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

/* This is an example of passing props */
const useStyles = makeStyles({
  buttonStyle: (props) => {
    return {
      color: props.cool ? "blue" : "red",
      backgroundColor: props.cool ? "orange" : "yellow"
    };
  }
});

function CoolButton({ cool }) {
  const classes = useStyles({ cool });
  return (
    <>
      <Button className={classes.buttonStyle}>Click me!</Button>
    </>
  );
}

export default CoolButton;

App.js

import CoolButton from "./CoolButton";

function App(props) {
  return (
    <>
      <CoolButton cool="true">Click me!</CoolButton>
    </>
  );
}

export default App;

https://codesandbox.io/s/cool-button-8its7

Let me know if you need further support.

Upvotes: 1

Omar Piga
Omar Piga

Reputation: 306

Try this:

const useStyles = props => makeStyles({
  buttonStyle: {
      color: props.cool ? "blue" : "red",
      backgroundColor: props.cool ? "orange" : "yellow",
  },
});

And call it:

const classes = useStyles(props)();

Upvotes: 0

Evgenii
Evgenii

Reputation: 143

For passing props to your styles you should pass props directly to useStyles method:

const classes = useStyles(props);

or

const classes = useStyles({ someSpecificProp });

Upvotes: 0

Related Questions