Here is a unique rewrite:"Adjusting the prop of a Material UI Button component depending on screen size breakpoints can be achieved by utilizing

While using the Material UI Button component, I encountered an issue with conditionally determining the variant of the button based on screen size. Specifically, I want the variant to be 'outlined' on medium and larger screens, and no variant at all on smaller screens. My current approach involves a class component, and after researching various solutions, I found suggestions such as using the useMediaQuery method in functional components. However, converting my large class component to a functional one seems daunting and may lead to confusion. I also attempted to use a ternary operator like this:

const variantType = theme.breakpoints.down("md") ? '' : 'outline';

<Button variant={variantType}>
       Food Pick
 </Button>

Unfortunately, this method did not produce the desired outcome. Are there any alternative approaches to achieve this?

Update: After attempting to wrap the component in a functional component, I encountered an error:

https://i.stack.imgur.com/LXwS2.png

import { withStyles, withTheme, useTheme } from '@material-ui/core';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import { PulseLoader } from 'react-spinners';
import Icon from '@material-ui/core/Icon';
import Chip from '@material-ui/core/Chip';
import useMediaQuery from '@material-ui/core/useMediaQuery';



const styles = theme => ({
  beta: {
    height: '17px',
    fontSize: '12px',
    marginLeft: '10px'
  },
  scrollContainer: {
    flex: 1,
    maxHeight: '400px',
    minHeight: '300px',
    overflowY: 'auto'
  },
  progressContainer: {
    height: '350px',
  },
  modalDescription: {
    color: theme.palette.text.secondary,
    marginTop: '20px',
  },
  button: {
    marginTop: '20px',
    marginLeft: '10px',
    marginRight: '10px',
  },
  smartSuggestContainer: {
    textAlign: 'right',
    paddingRight: '35px',
    [theme.breakpoints.down('xs')]: {
      display: 'flex',
      justifyContent: 'center',
      flexDirection: 'row',
      margin: '40px 0'
    },
  },
});

export default function MyComponentWrapper({ ...rest }) {
  const theme = useTheme();
  const mediumScreen = useMediaQuery(theme.breakpoints.down('md'));
  return <FoodDescriptions {...rest} mediumScreen={mediumScreen} />;
}

class FoodDescriptions extends Component {
  static PAGE_SIZE = 25;

  constructor(props) {
    super(props);

    this.state = {
      showFoodDescriptionsModal: false,
      dataLoaded: false,
      data: [],
      page: 0,
      sortBy: 'return',
      sortDir: 'desc',
    };
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeypress);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeypress);
  }

  fetchData = async (page, sortBy, sortDir) => {
    const { currentBotId } = this.props;
    const offset = page * FoodDescriptions.PAGE_SIZE;
    const data = await getFoodDescriptions(currentBotId, sortBy, sortDir, FoodDescriptions.PAGE_SIZE, offset);
    this.setState({
      dataLoaded: true,
      data,
    });
  };

  handleKeypress = (e) => {
    const { showSnartConfigsModal } = this.state;
    const { key } = e;
    if (key === 'Escape' && showSnartConfigsModal) {
      this.closeModal();
    }
  };

  applyConfig = (botId, params) => {
    const { updateConfig, botConfig, actions } = this.props;
    updateConfig({ name: botConfig.name, config: Object.assign(botConfig.config, params) });
    this.closeModal();
    actions.showNotification({ data: 'Configuration has been applied' });
  };

  openModal = () => {
    const { page, sortBy, sortDir } = this.state;
    this.fetchData(page, sortBy, sortDir);
    this.setState({
      showFoodDescriptionsModal: true,
    });
  };

  ...

  
connect(mapStateToProps, mapDispatchToProps)(withTheme()(withStyles(styles)(FoodDescriptions)));

Answer №1

Have you considered creating a functional component that utilizes the useMediaQuery hook to return a responsive Button?

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

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

Modify parent component state when input in child component changes in React

I am working on a parent component called NewPetForm: class NewPetForm extends React.Component { state = { name: '', age: '', animal: '', breed: '' }; render() { ...

Unexpected background image slideshow appearance

I am encountering an issue with my slideshow where the last image briefly appears before the first image loads in a continuous loop. The offset of the initial image causes it to start at the middle of the window, and in Google Chrome and Safari, subsequent ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

Using anti-cache code in jQuery's getJson function

During an interview, I was presented with the following question: Can you provide a one-liner code showing the proper syntax to add an anti-cache code to all jQuery getJson calls in a project without individually adding it to each call? I must admit th ...

Webpack Is Having Trouble Parsing My JavaScript Code

I recently started using webpack and I'm struggling to get it to work properly. I haven't been able to find anyone else experiencing the same issue as me. Every time I attempt to run "npm run build" to execute webpack, I encounter this error: ER ...

barchart rendered in SVG without the use of any external libraries

Creating a stacked barchart with SVG and HTML without relying on any third-party library has been quite a challenge. Despite searching extensively online, I have not come across a single resource that demonstrates how to build a stacked bar chart using pla ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

Ensure the text value of a collection of web elements by utilizing nightwatch.js

Recently, I started using nightwatch.js and I am trying to retrieve a list of elements to verify the text value of each element against a specific string. Here's what I have attempted: function iterateElements(elems) { elems.value.forEach(funct ...

How do I resolve the issue of unable to align the element correctly?

I am struggling to create a hamburger menu icon and align it using flexbox. Unfortunately, the icon is not aligning properly as it is going beyond the menu and the browser screen with an odd top indent. Below is the code I have written: * { margin: 0 ...

What is the best way to achieve a curved outer edge for a rectangle using CSS?

I am trying to style the header and footer of my website, which is built using a SAAS CMS. Unfortunately, I am unable to change the HTML structure, but I can add custom CSS. My goal is to create curved headers and footers with upward and downward curves. I ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

What steps should be taken to secure the routes within a React application that is dependent on Firebase for its backend operations

I'm looking for a quick way to secure the routes and manage user roles, authorisation, and authentication within a React website. I need to control which buttons on the AppBar are visible based on the user's role, but so far querying the database ...

Add a JQuery function to the button element in the HTML code

Currently, I am experimenting with AJAX to load a series of consecutive pages within a main page. The process is illustrated in the image below: Thanks to the guidance from this community, I have learned how to call content from other pages by utilizing t ...

CSS experts caution that the addition of margin and padding can cause the screen to jump

When I apply margin and padding to this class, it starts glitching like in the second GIF. However, if I remove margin and padding everything works fine, but I do need them for styling purposes. What could be causing this issue and how can I resolve it? ...

Error message stating "The file 'routes-manifest.json' was not found during NextJs deployment on Vercel"

My Next.js application was functioning correctly until I added some files to update my code. Now, it is failing to deploy on Vercel and showing this error message: https://i.stack.imgur.com/2y7CB.png Despite searching online for solutions, I haven't ...

The functionality of create-react-app is currently being hindered by postcss issues

Recently delving into the world of React, I embarked on a new project using create-react-app. After setting up the app, I proceeded to run npm start. To my dismay, an error message popped up: Error: Cannot locate module '~/Desktop/forms-test/node_mo ...

Leverage a single JavaScript file across all Vue components without the need for individual imports

My project includes a JavaScript file called Constant.js that stores all API names. //Constant.js export default { api1: 'api1', api2: 'api2', ... ... ... } Is there a way to utilize this file without having to impo ...

Ways to prevent other users from clicking or modifying a particular row

I have a data table in my project that will be accessed by multiple users simultaneously. My requirement is that once a row is selected and edited by one user, it should become unclickable for other users who are also viewing the same page or data table. ...

In Javascript, ensuring a stopping condition for a recursive function that is looping through JSON data

I am having trouble figuring out how to set the break condition for this recursive function. Currently, the function is causing the browser to freeze (seems to be stuck in an endless loop). My goal is to create a series of nested unordered lists based on ...