4

I want to remove the outlined variant at the small medium and down breakpoint. To do this, I have tried to do the following:

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

<Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
  Buy
</Button>;

This does not do the job. I have tried researching and no one seemed to ask this question before. So here is the first of its kind. lol

kenny335
  • 87
  • 8

2 Answers2

4

You can do this by using the useTheme and the useMediaQuery hooks from Material UI.

import { Button, useTheme, useMediaQuery } from '@material-ui/core'

export default function App() {
  const theme = useTheme();
  const mediumDown = useMediaQuery(theme.breakpoints.down('md'));

  return (
    <div className="App">
      <Button name="buyFood" variant={mediumDown? 'text' : 'outlined' } onClick={this.openFoodModal}>
        Smart Suggest
      </Button>
    </div>
  );
} 

Edit Button variant controlled by media query

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
Richard Hpa
  • 2,353
  • 14
  • 23
3

You can access your theme settings with the useTheme hook if you have custom theme.

After that you only have to compare the current window width with your breakpoint.

To do this you can simply write a hook that gives you the current window width.

Here is an elegant solution from @QoP

This could then look like this:

./App.js

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

export default function App() {
  const theme = useTheme();
  const width = useWindowWidth();

  const variantType = width < theme.breakpoints.values.md ? "text" : "outlined";

  return (
    <div className="App">
      <Button name="buyFood" variant={variantType} onClick={this.openFoodModal}>
        Smart Suggest
      </Button>
    </div>
  );
}

./useWindowWidth.js

import { useState, useEffect } from "react";

const getWindowWidth = () => window.innerWidth;

export default function useWindowWidth() {
  const [windowWidth, setWindowWidth] = useState(getWindowWidth());

  useEffect(() => {
    function handleResize() {
      setWindowWidth(getWindowWidth());
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowWidth;
}

Live demo:

Edit heuristic-dirac-otz93

yun_jay
  • 1,050
  • 6
  • 20