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

Solution for accessing the callee function in JavaScript slide down operation

While exploring a tutorial from CSS Tricks about animating section height, I came across a solution that I would like to implement in my Angular 2 application. Here is the function responsible for expanding sections in my app: expandSection(element) { / ...

Selecting multiple default values in a Material UI Radio button group

<RadioButtonGroup name={currentQuestion.id.toString()} onChange={this.onRadioBtnClick} valueSelected={answerObject ? answerObject.answer : ''} > Hi there! I have a question about the valueSelected prop in the RadioButtonGroup. ...

Leveraging Ajax in Django to communicate with the backend and showcase the outcome

I need assistance with implementing ajax functionality to send user input to a Django backend for text processing, and then display the results. However, due to my limited experience with ajax, I'm struggling to figure out where I'm going wrong. ...

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

Utilize jQuery to extract the content, rearrange the content, and then encapsulate it within fresh

I attempted all day to rearrange this menu the way I want, but since I am new to jQuery, I'm facing some challenges. Here is what I am currently trying to achieve: Inside the last td.top of this menu, there are 3 ul.sub li items. I aim to extract ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Firebase Function deployment encountered an issue during the build phase, despite the predeploy process

My react.js project includes Firebase functions that are configured in a sub-folder called root/functions. These functions are written in typescript and have paths option set in tsconfig.json. In my functions/index.ts file, I import files from various loca ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

Creating a stunning image carousel in Vue by integrating a photo API: step-by-step guide

Trying to figure out how to create an image carousel in Vue using photos from an API. Currently able to display the photos using: <section class="images"> <img v-for="image in images" :key="image.id":src="image.assets.large.url"> &l ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { return null; } retu ...

Achieving two-way data binding in a directive without using an isolated scope

Implementing scope: { ... } in a directive creates an isolated scope that doesn't inherit from its parent. However, my usual practice has been to utilize this for easily declaring HTML attributes with bi-directional data binding: scope: { attr1: ...

What is the best way to extract all "conditions" nested under the key "logic" at the 0th index in a JSON object?

I need to manipulate a nested object by removing every "condition" where the key is "logic" and the value is 0 from it. Here is an example of the object structure: Original input: [ { "conditions": [ { "logic": "AND", "paramet ...

When working in MongoDB, the term "undefined" is not used for data; instead, the uploaded file data is

Exploring the world of MERN, I decided to create an image uploader website. Everything was going smoothly until I encountered a problem while trying to upload an image with text input from React. Despite successful uploading of the image, the text appear ...

angular trustAsHtml does not automatically insert content

Two divs are present on the page. Upon clicking button1, an iframe is loaded into div1. The same applies to button2 and div2. These iframes are loaded via ajax and trusted using $sce.trustAsHtml. This is how the HTML looks: <div ng-bind-html="video.tru ...

Remove the unnecessary space at the bottom of the Mat Dialog

I'm currently utilizing Angular Material within my Angular application. One issue I am facing is the excessive whitespace at the bottom of a dialog that displays information about a post. How can I reduce or eliminate this unnecessary space? Take a l ...

Is there a method to measure the time it takes to download a script apart from its actual execution time

I am looking to track timing variables for my primary JavaScript load. One approach could be: <script> performance.mark('script-start') </script> <script src="something.js"></script> Later in something.js, inc ...

Combine going to an anchor, performing an AJAX request, and opening a jQuery-UI accordion tab all within a

My goal is to have the user click on the hyperlink below, which will (1) anchor to #suggestions, (2) navigate to the url suggestions.php?appid=70&commentid=25961, and (3) open the jquery-ui accordion #suggestions. However, I am facing an issue where c ...

The JSON.stringify() method is overwriting the file object with a blank one

COMPLEXITY Hey everyone, I could really use some assistance in resolving this intricate problem. I am working on an application using a combination of Spring Boot v2.0.5 and React.js v15.6.2, ReactDom v15.6.2, React Bootstrap v0.32.4. The communication be ...

Guide on how to store a CSS image in a server using PHP

Looking to create a button generator using JavaScript on my website, similar to the one found here http://css-tricks.com/examples/ButtonMaker/. In addition to generating buttons, I also want to include a save button so that users can save the button image ...

Comparing Encrypted Passwords with Bcrypt

Encountering an issue with comparing passwords despite accurately storing the hashed password during registration. Database - MongoDB Node.js version - v18.17.0 Bcrypt version - 5.1.1 Below is my userSchema: const userSchema = new mongoose.Schema({ u ...