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

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...

What is the compatible version of Material UI with React 15.5.4?

Currently working on a project in React version 15.5.4 and looking to integrate Material UI into the app. However, I keep encountering an error stating that React version 16.3.0 or higher is required whenever I attempt to install and incorporate Material ...

Having trouble grasping the inner workings of code while iterating through a JSON array in ReactJS

Currently, I am immersed in a school project that requires me to develop a simple CRUD web application. After weighing my options, I decided to utilize Spring Boot + ReactJS for this endeavor. The progress has been smooth so far, but I must admit that part ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

I'm facing difficulty in assigning props because of the specific nature of generics in Typescript

My goal is to create a Higher Order Component (HOC) that can control a component which relies on certain props to function properly. To elaborate: I want to build a HOC that takes a component expecting props value and onChange, and modifies it so that the ...

The issue with Next.js is that cookies are not being transmitted along with fetch requests, even when credentials are

I've been developing a Next.js application that originally started as a regular React app created using create-react-app. I'm facing an issue where the cookies are not being sent with my fetch request to the server, despite setting credentials: & ...

Is it possible to apply a CSS transform without erasing the existing transform?

Looking for a solution: elem transform translateY(5px) scale(1.2) I want the element to move down an extra 5px on hover elem:hover transform translateY(5px) Is there a way to achieve this without knowing the previous state of the transform? Appr ...

A custom hook is not functioning as expected

I've encountered an issue with the useCart() function, as it's giving me an error message stating that it is not a function. Here is the code snippet where I'm using it: "use client"; import React, { createContext, useReducer, use ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

Icons in React are used to visually represent various actions

I am facing an issue with the React icons I imported on my personal website. They are not displaying at all. Despite reinstalling React Icons multiple times, with and without --save, the problem persists. I have thoroughly checked both the node_modules dir ...

Pushing a React application to Heroku for deployment

I am working on a React.js application that relies on an API built with Django Rest Framework. In my local development setup, I have the React and Django applications decoupled, each running on its own server using different ports. My question is, can I ...

Add the unique identifiers of objects to an array when a checkbox is selected within a React.js Functional Component

I am working with an array where I need to add the object IDs when a checkbox is checked, and remove the IDs when the check mark is removed by an admin. <Form.Label>Select Package/s:</Form.Label> {packages.map((item) => ( <Form.Check ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

Displaying an image that spans the entire width of the browser

I'm currently working on a WordPress site and have encountered an issue with the header image. I want it to span the full width of any browser window. The existing code in the parent theme is as follows: background: url("/test/wp-content/themes/Howt ...

Rotate CSS elements dynamically using jQuery

I'm trying to figure out how to change the rotation value of an image element in my code. Currently, the rotation is set to 315 degrees, but I want to change it to 0 when a click event occurs. Can anyone help me with this? ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Delving into the World of CSS

I have been working on changing the background image using this JavaScript code, but I am not sure what to reference in the CSS file. Despite reading through everything, my screen still remains blank. $(function() { var body = $('body'); var bac ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...