Toggling designs with a simple click



I'm currently working on a ReactJS project and I'm trying to figure out how to change the color of a button when it's clicked. I've heard about the Ripple API, but I find it quite complex to use. Can anyone offer some advice on how I can achieve this?

So far, I've attempted to create two elements - a parent and a child - and changed the background color of the child element to transparent on click. However, I also have an 'classes' object that should handle changing the class if the button is active, but it doesn't seem to be working properly. Here's my code snippet:

insert modified code here...

and here are the styles:

insert modified styles here...

Answer №1

Material UI Core for ReactJS

The information provided in the documentation is excellent. I have revised my response to meet the specific requirements of this query. Additionally, I've included two general solutions that may prove helpful to others encountering a similar issue.

Customized Solution:

This solution involves altering the background color of a button from classes.buttonDefaultRoot (a color specified by the question owner) to a gradient outlined by the individual behind this question.

To begin, create a variable within the state that will store the desired value. You can name it as you wish; in this case, let's refer to it as bgButton and set it to

this.props.classes.buttonDefaultRoot
:

state = {
  bgButton: this.props.classes.buttonDefaultRoot,
}

Next, define a function to manage the click event. Name it accordingly; here, we'll use handleClick:

handleClick = () => {
    const { classes } = this.props;
    this.setState({ bgButton: classes.parentRoot.auxClass });
};

Several actions occur within this function. Initially, props are destructured to create a new constant named classes holding the same value as this.props.classes. This contains a set of objects defining CSS styles for buttons, margins, etc, which can be accessed like any other prop to get the style value. For instance, classes.buttonDefaultRoot provides access to the button style.

Lastly, render the button. Within the render method, fetch bgButton from the state:

render() {
  const { bgButton } = this.state; 

Assign the className of the button to bgButton and add the onClick functionality following Material UI Core documentation:

<Button variant="contained" color="primary" className={classNames(bgButton)} onClick={this.handleClick}>Button Name</Button>

Combining all components yields:

import React, { Component } from "react";
import Button from "@material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "@material-ui/core/styles";

export default theme => ({ ... }) //excluded remaining code for brevity

class MyButton extends Component {
  state = {
    bgButton: null
  };
  handleClick = () => {
    const { classes } = this.props;
    this.setState({ bgButton: classes.parentRoot.auxClass });
  };
  render() {
    const { bgButton } = this.state;
    return (
      <div className={classes.container}>
        <Button
          variant="contained"
          color="primary"
          className={classNames(bgButton)}
          onClick={this.handleClick}
        >
          Custom CSS
        </Button>
      </div>
    );
  }
}

MyButton.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(MyButton);

General Solution

This alternative suits those interested in utilizing predefined colors such as default, primary, secondary, inherit. The implementation eliminates the need for PropTypes or className imports, focusing solely on changing the color from default blue to predetermined pink.

state = {
  bgButton: "primary", 
} 
handleClick = () => {
  this.setState({ bgButton: "secondary" }); 
} 

render() {
  const { bgButton } = this.state; 
  return(
   ...
   <Button
     onClick = {this.handleClick} 
     variant = "contained"
     color={bgButton}
    > ..etc.

General Solution 2

For applying custom styles to the button, import PropTypes and classNames then follow the approach outlined in the tailored solution above. Syntax and class names may differ, but adhere closely to the documentation for easy comprehension and adjustments if required.

    import React, { Component } from "react";
    import Button from "@material-ui/core/Button";
    import PropTypes from "prop-types";
    import classNames from "classnames";
    import { withStyles } from "@material-ui/core/styles";
    import purple from "@material-ui/core/colors/purple";

    const styles = theme => ({
      container: {
        display: "flex",
        flexWrap: "wrap"
      },
      margin: {
        margin: theme.spacing.unit
      },
      cssRoot: {
        color: theme.palette.getContrastText(purple[500]),
        backgroundColor: purple[500],
        "&:hover": {
          backgroundColor: purple[700]
        }
      },
      bootstrapRoot: {
        boxShadow: "none",
        textTransform: "none",
        fontSize: 16,
        padding: "6px 12px",
        border: "1px solid",
        backgroundColor: "#007bff",
        borderColor: "#007bff",
        fontFamily: [
          "-apple-system",
          "BlinkMacSystemFont",
          '"Segoe UI"',
          "Roboto",
          '"Helvetica Neue"',
          "Arial",
          "sans-serif",
          '"Apple Color Emoji"',
          '"Segoe UI Emoji"',
          '"Segoe UI Symbol"'
        ].join(","),
        "&:hover": {
          backgroundColor: "#0069d9",
          borderColor: "#0062cc"
        },
        "&:active": {
          boxShadow: "none",
          backgroundColor: "#0062cc",
          borderColor: "#005cbf"
        },
        "&:focus": {
          boxShadow: "0 0 0 0.2rem rgba(0,123,255,.5)"
        }
      }
    });

    class MyButton extends Component {
      state = {
        bgButton: null
      };
      handleClick = () => {
        const { classes } = this.props;
        this.setState({ bgButton: classes.cssRoot });
      };
      render() {
        const { classes } = this.props; 
        const { bgButton } = this.state;
        return (
          <div className={classes.container}>
            <Button
              variant="contained"
              color="primary"
              className={classNames(bgButton)}
              onClick={this.handleClick}
            >
              Custom CSS
            </Button>
          </div>
        );
      }
    }
MyButton.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(MyButton);

Constructors and method binding are no longer necessary. This guideline should simplify the process.

Trust this information proves useful.

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

Shift div position when clicked and employ jQuery animations

I have been attempting to add animation to a DIV element by using jQuery. The goal is to move the DIV from the center to the left when it is clicked, but I am encountering some issues. The parent div has a position of "relative", and my initial idea was to ...

Leveraging window.print() in a React application: the best practices for implementation without triggering deprecation warnings

I'm currently utilizing window.print() within a React JS app. My goal is to have the print modal trigger after the data has been downloaded and the content rendered. When using Chrome, I noticed a warning in the console: The use of 'print()&a ...

How come the hover effect is not functioning properly following the addition of padding to

I have set a padding top of 120px, but for some reason the hover effect is not working properly. Can anyone help me troubleshoot this issue? Here is the code snippet: 'use client'; // eslint-disable-next-line no-unused-vars import React, { useSta ...

Alignment of Material within Two Adjacent Divisions

I'm having trouble centering the content within two side-by-side divs. It seems like the content in each of these divs is centering towards one another, which is not what I want. I've created a main container and placed two divs inside it. The ...

Subheaders that stay in place while scrolling through a table with a stationary header

My goal is to design a table with a fixed header that allows the body to scroll under the header. While this is a common design, I am facing the challenge of implementing sticky subheaders. These subheaders should scroll along with the table until they rea ...

Is there a way to display shortened text only when hovering without altering the height of the list box?

Here is my script for a vue component : <template> ... <b-card-group deck v-for="row in formattedClubs"> <b-card v-for="club in row" img-src="http://placehold.it/130?text=No-image" img-alt="Img ...

Guide to making control bar fade out when video is paused on video.js

Is there a way for the control bar to automatically disappear when the video is paused? Thank you in advance! ...

Update the class name by utilizing template literals

I'm currently in the process of mastering template literals as I have a project where I need to utilize them. However, I seem to be encountering an issue that I can't quite figure out. Here is the code that is currently working: const classes = ...

What is the best way to constrain the ratio of a full-width image display?

I am in need of a solution for displaying an image at full width inside a frame with a 16:9 aspect ratio. The image needs to be centered within the frame and adjust responsively when resizing the screen. My preference is to achieve this using just CSS. ...

Is it possible to move the Material UI TableSortLabel Arrow to the opposite side?

My table has columns that are both right aligned and left aligned, and I need them sorted. When the column is right aligned, I would like the sorting icon to be on the left side of the header. Otherwise, there is an awkward empty space where the icon shoul ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

Achieving uniform cell height distribution in Foundation XY-grid using flexbox

When utilizing the Foundation XY-grid, I encountered an issue with distributing cell heights evenly within a nested grid-y inside a cell using the .auto class on the parent cell. In a scenario with 2 cells in a grid-y, the desired outcome is 50%/50%. This ...

Tips for positioning elements within an ng-repeat list using absolute positioning?

Here is the HTML code: <div class = "container"> <form ng-submit = "createSticky()"> <input ng-model="formData.data" type="textarea" name="sticky_content" placeholder="add sticky text" required="true"/> <input ng-model= ...

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

Is there a way for me to change the color of a Checkbox in Material UI?

Currently, I am incorporating Material UI into my project and have encountered an issue with the Checkbox element. Placed within a div with a black background, the Checkbox itself appears in black as well. I would like to change the color of the Checkbox ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

How can the parent div be made transparent without affecting the child div's visibility?

When applying opacity to a parent div, I noticed that it also affects the child div. My intention is to only apply opacity to the parent div. I have set up separate divs for this purpose. <div id="container" style={{backgroundImage:"url('/images ...

Error: The provided `anchorEl` property for this component is invalid

While working on my React 18.2 app with MUI 5.10.5, I encountered an issue trying to create a <Menu /> element that should open when a button is clicked. The menu does appear, but the positioning seems off as it displays in the top-left corner of the ...

Transferring data from a child component to a parent component following a click event in the child component that activates a function

When a "click event" occurs on the chevron <button> within the <Nav/> component, it triggers the nextTitle(length) function in the custom hook useNextTitle.js. This function updates the value of val, which is then returned by useNextTitle.js. T ...

SSL/HTTPS issues impacting Server-Sent Events (SSE)

Greetings, I am currently in the process of developing a React web application that is designed to receive SSE data from an Express server working with Nginx. SERVER.JS const express = require('express'); const bodyParser = require('body-p ...