How to hide/show elements at certain breakpoints with Material UI?

Viewed 4459

I want to show/hide elements on certain break points, like what I would do with Bootstraph or Zurb Foundation.

I see in the documentation here https://material-ui.com/system/display/#api we add

display={{ xs: 'block', md: 'none' }}

to our elements. I have done this, but I don't get any results - no hiding/showing elements, no errors, no compilation problems.

Would anyone know how this is done?

My code is:

import React from 'react'
import PropTypes from 'prop-types'
import makeStyles from '@material-ui/core/styles/makeStyles'
import Button from '@material-ui/core/Button'

const useStyles = makeStyles(styles)
const PhoneActionLink = ({ children, prefix, href, value, display, isFirst, ...other }) => {
  const classes = useStyles()

  return (
      <Button
        display={{ xs: 'block', md: 'none' }}
        {...other}
      >
        {children}
      </Button>
    </div>
  )
}
2 Answers

Here you go with a solution

import React from 'react'
import PropTypes from 'prop-types'
import makeStyles from '@material-ui/core/styles/makeStyles'
import Box from '@material-ui/core/Box'
import Button from '@material-ui/core/Button'

const useStyles = makeStyles(styles)
const PhoneActionLink = ({ children, prefix, href, value, display, isFirst, ...other }) => {
  const classes = useStyles()

  return (
    <Box component="Button" display={{ xs: 'block', md: 'none' }} m={1}>
      {children}
    </Box>
  )
}

Wrap the Button component within Box component.

The answer strictly depends on the version of MUI you're using.

The accepted answer should work for MUI v4 and prior versions, but didn't work for me (MUI v5).

I dug into the documentation From the official MUI website and found that the following code works for me:

<Box sx={{ display: { xs: 'block', md:'none' } }}>
   {children}
</Box>

I'm guessing that the sx attribute allows you to modify some of the CSS properties based off specific breakpoints.

I'm no expert so I can't fully explain the solution, but I'm hoping that this solution helps another person out there.

Related