Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

javascript - hidden attribute ignored on Button component

I'm trying to hide a Material-UI Button component by adding the hidden attribute, but it appears the attribute is ignored. I've used the hidden attribute on other Material-UI components such as Typography, Grid and Box and there it works fine. Below is a simplified snippet of my code. Click here to try it out on CodeSandbox.

<Typography hidden={loading}>
  Works. This text is not displayed when `loading` is truthy.
<Button hidden={loading}>
  Doesn't work. This Button is still there!
</Button >

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TLDR: Don't use the hidden attribute. Use conditional rendering like {loading && <Component/>} or a style like <Component style={{ display: loading ? 'none' : undefined }} />

First, the hidden attribute has nothing to do with Material UI or React, but is a default HTML attribute from the web standard. Second, the hidden attribute is overridden if a display: ... style is applied to the same element. It doesn't matter if these styles are inline or coming from CSS. As a result, the hidden attribute is "ignored" by any Material-UI component that happens to set the display attribute.

You can try this on any of the examples from the official docs. For example, playing around with CodeSandbox you can see hidden work on Card, CardContent and Typography, but ignored on CardActionArea, CardMedia, CardActions and Button.

Considering the above it's best to avoid the hidden attribute as its behavior is different on a per-component basis. Moreover, if in any next version of Material UI a component is updated to use display internally, it'll change the semantics of hidden for that component and break stuff in your code base.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share