Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located after it has disappeared.

<Grid className={classes.container} style={{justifyContent: 'flex-end'}} item xs={12}>
            <Button className={classes.addImage} onClick={this.addPic}>
                <input 
                className={classes.takePic} 
                ref="file"
                id="takePic" 
                type="file" 
                accept="image/*"
                onChange={this.onChange}
                />
                Add 
                <br></br>
                Image

            </Button>
        </Grid>

Styling:

 addImage: {
    display: 'flex',
    backgroundColor: 'black',
    color: 'white',
    borderRadius: 90,
    height: 100,
    width: 100,
    justifySelf: 'flex-end',
    marginRight: '12.5%',
},

onChange function:

    onChange = () => {
    let newfile = this.refs.file.files[0];
    let reader = new FileReader();
    let url = reader.readAsDataURL(newfile);
    reader.onloadend = () => {
        this.setState({
            ...this.state,
            openModal: true,
            imgSrc : [reader.result],
            imageType: newfile.type,
            newfile: newfile,
            filename: `${this.props.user.id}_${Date.now()}`
        })
        console.log(newfile)
        console.log(this.state)

    }
}

addPic function:

addPic = () => {
        document.getElementById('takePic').click()
    }

Answer №1

It's important to proceed with caution when overriding the CSS for Material-UI's Button colors. Making changes without following the established pattern can lead to unintended consequences, especially on touch devices' "hover" state.

The snippet below showcases how Button's styles manage colors for the default "text" variant:

export const styles = theme => ({
  /* Styles applied to the root element. */
  root: {
    color: theme.palette.text.primary,
    transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {
      duration: theme.transitions.duration.short,
    }),
    '&:hover': {
      backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
      '&$disabled': {
        backgroundColor: 'transparent',
      },
    },
    '&$disabled': {
      color: theme.palette.action.disabled,
    },
  },
  /* Styles applied to the root element if `disabled={true}`. */
  disabled: {},
});

In your custom addImage class, you may have altered the button's backgroundColor to black and color to white without addressing the hover behavior. This could result in Material-UI's styling taking precedence during hover due to specificity, leading to unexpected outcomes, such as an invisible button against a white background on touch devices.

To avoid such issues, it's advisable to clearly define the hover effects, as demonstrated in this solution: How do I change the ripple background color on Button?.

For comprehensive insights into Material-UI's styling, refer to the Button source code: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Button/Button.js

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

Trouble encountered with card flip style login form in Vue.js, as the card is not maintaining its position properly during transition animations

Need help styling a login/signup component in Vue.js where flipping between the two cards isn't working smoothly. The transition is causing one card to move down and right while the other comes in from the bottom right. It's hard to explain the i ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

Clicking on a link initiates the dropdown menu for selecting an option

This project is specifically designed for mobile use, so there's no need to worry about how it will appear on desktop screens. In this project, I have an "a href" with an icon next to it that simulates a button. When a user clicks on it, a dropdown me ...

What is the reason for the square brackets in my json data?

My current project involves exploring the usage of JSON in conjunction with jQuery and MVC2. My goal is to generate JSON data for an AJAX post request to my controller. I have created an array using the following function: function getArguments() { var ar ...

Is there a possible method to obtain a smartphone number from a website?

Seeking a solution to retrieve the phone number of a device using HTML 5, JavaScript, or similar technology. Recently, I successfully obtained the coordinates of the device by incorporating the following JavaScript code: <!DOCTYPE html> <html> ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Table-styled div containing a horizontal scrolling div

I am currently in the process of developing a webpage with dual columns. The two columns are segregated into div containers, one labeled right and the other labeled left. These columns reside within a parent div called row, which is nested within a main di ...

Placing HTML text on top of a three.js renderer

I have been attempting to overlay HTML text onto my three.js sketch, but adjusting the z-index does not seem to be working. While I know that I could utilize innerHTML, the issue arises when I need to also use the onclick attribute, which is not the main f ...

What is the best method for converting nested arrays into a table format?

I am attempting to present my data in a tabular format with headers labeled key1 and key2. Below is the code I have written: render() { console.log((this.state.message)); const datamapping = Object.entries(this.state.message); cons ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

How to utilize datepicker in react-redux to compare dates

Incorporating the DateInput component into my Redux form has been quite a challenge: const MyDatePicker = ({ input, meta: { touched, error } }) => ( <div> <DatePicker {...input} dateFormat="DD-MM-YYYY" selected={input.value ? ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Exploring X3DOM nodes using d3.js

I'm attempting to loop through X3DOM nodes in D3.js, but I'm encountering an issue. Check out the code snippet below: var disktransform = scene.selectAll('.disktransform'); var shape = disktransform .datum(slices ...

What's the best way to integrate a Prisma object into the routing system of a NextJS 13 application

Currently using Prisma with SQLite, my User model stores id, name, and email fields. Within the file /alluser/page.tsx, there is a function implemented to fetch data from Prisma. export async function getAllUsers(){ const prisma = new PrismaClient( ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Tips for sending information from an HTML div to a function component in React

Seeking guidance on transferring properties from HTML to a React file. Here is the current code snippet: <html> <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16 ...

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

Insert information into an array within a mongoDB structure using the Mongoose library

Is it possible to add elements into an array in a mongoDB schema? For instance, in the given schema: var ProviderSchema = new Schema({ keyWords: [String] }); How can I insert data into the keyWords field using the specified route: app.put(&a ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...