Leveraging class names to dynamically apply CSS styles to components based on their props value

In the process of developing a collection of reusable components, I have utilized material-ui and styled them with CSS. One specific requirement is to dynamically set the width of a component through a prop passed into a custom button.

My goal is to leverage classnames in order to combine the const root style defined for MyButton (for features like colors and icons) with a dynamic sizeStyle that can adjust based on the prop provided.

  const sizeStyle: JSON =  { minWidth: "300px !important"};

  //always apply the buttonstyle, only apply the size style if a width prop has been supplied
  const rootStyle: Object = classNames({
    buttonStyle: true,
    sizeStyle: props.width
  });   

Despite my efforts, it seems that the style is not being applied to the first button on the page when a prop is passed through - even though the console indicates that both styles should be present.

View the sandbox here: https://codesandbox.io/s/css-styling-custom-muibutton-width-as-prop-36w4r

Thanks in advance!

Answer №1

To utilize the useStyles(props) function effectively, ensure that you pass props to it so that you can customize styles similar to using styled-components.

For more details, refer to the documentation: https://material-ui.com/styles/basics/#adapting-based-on-props

// eslint-disable-next-line flowtype/no-weak-types
const useStyles = makeStyles({
  root: {
    //    minWidth: "300px !important",
    color: "#565656",
    backgroundColor: "salmon",
    borderRadius: 2,
    textTransform: "none",
    fontFamily: "Arial",
    fontSize: 16,
    letterSpacing: "89%", //'0.09em',
    boxShadow:
      "0px 1px 5px 0px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)",
    "&:disabled": {
      color: "#565656",
      opacity: 0.3,
      backgroundColor: "#fbb900"
    },
    minWidth: props => `${props.width}px`,
  },
  label: {
    textTransform: "capitalize",
    display: "flex",
    whiteSpace: "nowrap"
  }
});

// eslint-disable-next-line flowtype/require-return-type
function MyButton(props) {
  const { children, ...others } = props;
  const classes = useStyles(props);

  return (
    <Button
      {...props}
      classes={{
        root: classes.root,
        label: classes.label
      }}
    >
      {children}
    </Button>
  );
}

Check out the modified version of this code on your sandbox: https://codesandbox.io/s/css-styling-custom-muibutton-width-as-prop-pcdgk?fontsize=14&hidenavigation=1&theme=dark

I hope this information is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an error when attempting to start npm after creating a react app

I've been attempting to create a new React app but I'm having trouble running `npm start`. I don't quite understand the error message, so I'm hoping someone can help. I also tried deploying on GitHub yesterday (if that information is he ...

Error: The server selection process has encountered an unexpected issue

Embarking on my journey with MongoDB and the MERN stack, I turned to these tutorials for guidance: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1 https://www.youtube.com/watch?v=7CqJlxBYj-M ...

Utilize the get method to showcase data in a material UI table for a React application

Just starting out with React. Managed to create a table component with hard-coded data. However, I now have all the data stored in table.json. Can someone guide me on how to fetch values from table.json using an axios get request an ...

Monitoring Changes in an Array of Objects with Angular's $watch Feature

Imagine having an array of animal objects linked to the scope. Each object contains a 'name' field and a 'sound' field. After that, I set up a $watch on the array with the objectEquality flag set to true (the third argument). Then, in ...

Connecting factors

Let me simplify what my code does: var list = { "group":{ "subgroup1":[{"name1":"Jimmy","name2":"Bob"}], "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}] } } function group(group,name){ var link ...

Tips on targeting a node that is dynamically generated within a function and styling it externally

Is there a way to style or change divs created within a function, but without making the change within that same function? Since variables are in the local scope of functions, it can be challenging to access these created divs for future styling or changes ...

Adjust the size of H1, H2... tags based on their own specifications, rather than the surrounding element

I have run into a bit of a conundrum with my code and cannot seem to find the right solution. Here is what I currently have: <div id="bloquetexto4" class="bloquetexto"> <H2><b>TITULO</b></H2> <p>Texto bla bla bla.</p ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

Is there a way to customize the default MuiCheckbox icon in theme.ts?

How can I customize the icon default prop for Mui checkbox? I followed the instructions provided here and used a snippet from the documentation: const BpIcon = styled('span')(({ theme }) => ({ borderRadius: 3, width: 16, height: 16, .. ...

Creating a unique carousel design using only CSS in Bootstrap

Trying to create a CSS effect to enhance Bootstrap, I noticed that it only works correctly when clicking the right arrow. Whenever I click the left one, nothing happens. I'm not sure where I made a mistake, can anyone help me spot it? Thanks in advanc ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Choosing the Right Alignment for Your Selection Box

How can I adjust the alignment of the select box to make it inline with the others? I also need to apply this alignment to the three option input boxes. CSS: #newwebsiteSection, #websiteredevelopmentSection, #otherSection{ display:none; } #newwebsite ...

`Toggle full screen navigation visibility upon clicking on a BrowserRouter Link`

Currently, I am in the process of setting up a navigation system for a React app that is under development. The navigation system consists of a full-screen overlay that appears when a button in the header is clicked. To control the visibility of the over ...

Utilizing the document.createDocumentFragment() method along with innerHTML for manipulating a Document Object Model (

I am currently in the process of creating a document fragment using the code below: let fullHTMLDocument = '<!doctype html> <html><head></head><body><h1>hello world</h1></body></html>'; let f ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

Creating a PHP JSON response that incorporates an HTML layout is a dynamic

I'm having some trouble with a certain issue: I am attempting to develop a jQuery/AJAX/PHP live search bar. Although I am successfully calling search.php, the response displayed in the console always includes the contents of my master.php file (which ...

Issue encountered with AJAX multiple image uploader

I'm attempting to create an PHP and JavaScript (jQuery using $.ajax) image uploader. HTML: <form method="post" action="php/inc.upload.php" id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file[]" a ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...

Could you provide suggestions on how to update the content of an HTML tag within a Vue component?

I am new to Vue.js and struggling to grasp its concepts. I am interested in finding a way for my custom Vue component (UnorderedList) to manipulate the content within it. For example, if I have <p> tags inside my component like this : <UnorderedL ...