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

Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue? ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

Is there a way to disregard the active region of a child element while the parent is active?

Currently, I am working on building a to-do list application using React. In the CSS styling, I have implemented an animation for when an li element is active, causing it to expand in height. The issue arises from the fact that I have also set up an onClic ...

Tips for integrating tsconfig with webpack's provide plugin

In my project, I have a simple component that utilizes styled-components and references theme colors from my utils.tsx file. To avoid including React and styled-components in every component file, I load them through WebpackProvidePlugin. Everything works ...

Is it possible to use file upload for sending via Ajax's POST method?

Let's talk about the scenario at hand Here's what happens in a single form: 1) The user clicks on the 'browse' button, which opens a dialog to select an image file for uploading. Example: input id='img_upload' name="ufile" ...

Unable to fetch information from the local host using an AJAX request and PHP script

I'm having trouble retrieving the <p> elements echoed in my PHP script. I need a solution that allows me to style these <p> nodes using a JavaScript function without refreshing the page. Can someone help me with this issue? Here is my PHP ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

How can I combine HTML and CSS in a single request using the sendFile method in Express?

const app = require('express')(); app.get('/', function(req, res) { res.sendFile(__dirname + "/" + "index.html"); }); <link rel="stylesheet" href="style.css"> I utilized the Node.js code above to send an HTML file. In order to ...

Omit the use of "default" when importing a JSON file in Vite+React with Typescript

Each time I attempt to import a JSON file, it seems to enclose the JSON within a "default" object. When trying to access the object, an error message displays: Property 'default' does not exist on type... I have already configured resolveJsonMod ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

When executing the command "npm or pnpm run dev", no output is shown on the screen

I'm currently using Windows 11 and working on a Next.js project. After initializing my project with "npx create-next-app@latest", I ran the command "npm run dev" but nothing appeared even though the initialization was successful. Click here to view i ...

Struggling to locate components in your React, Next.JS, and Typescript project? Storybook is having trouble finding them

I have set up Storybook with my Next.js, TypeScript, and React project. The main project renders fine, but Storybook is breaking and giving me the error message: "Module not found: Error: Can't resolve 'components/atoms' in...". It appears t ...

Locate a row in an unselected data table using Jquery based on the value in a td

Is there an efficient way with jQuery to locate a td in a "legacy" datatable that contains my search value, and then navigate up the row tr? I am currently using $('#modalTable tbody').dataTable()[0].rows to retrieve all rows and then iterate th ...

"Challenges with Full-Width Dropdowns in Multi-level Mega Menus

I am currently attempting to design a multi-level mega menu that spans the full width of the screen, while keeping the content within it restricted to a maximum width of 1240px. I have managed to set the content to the maximum width, but I am facing challe ...

Forward checkout.session items from Stripe webhook to Supabase

Currently, I am utilizing next.js in conjunction with Stripe webhooks to insert checkout sessions into Supabase for generating a customer's order history. While I have successfully managed to store the entire order information in a table named 'o ...

Difficulty arises when Jest tests struggle to interpret basic HTML tags within a React Component

When running test runs, issues arise when using standard HTML tags with Jest. My setup includes Babel, Webpack, Jest, and React Testing Library. To enable jest, I have installed a number of packages: "@babel/plugin-proposal-class-properties": "7.8.3", "@ ...

Should one consider using the Express app.use() method within an asynchronous callback function?

Seeking advice on a recommended best practice. I recently developed an Express server that generates a JWT and sends it to the client whenever they hit an API endpoint. To maintain modularity, I separated the route handler into its own module and exporte ...

Retrieve the most recently added child from the Firebase cloud function

Seeking assistance in retrieving the most recently added child in a cloud function. Below is the code snippet I am using and I'm curious if there is a specific function or query I can utilize to achieve this task without having to iterate through each ...

Clickable Material UI TextField with embedded URL

Is it possible to pass a hyperlink along with text contents as a value to the TextField component in material-ui, but have it render as an actual clickable link rather than just as a string? (see image below) component: import { TextField, Link } from &a ...

.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as t ...