Prevent the parent component's ripple effect from being activated by the child component

If I have a simple code snippet like the following:


<ListItem
  button={true}
>
  <Typography variant='caption' color='primary'>
            {value}
  </Typography>
  <Button
    onClick={foo}
  >
    Button
  </Button>
</ListItem>

When clicking anything inside the ListItem, the ripple effect is triggered as expected. However, when clicking the button, I do not want the ripple effect of the parent component to be activated. How can this be accomplished?

Answer №1

To prevent event propagation, implement event.stopPropagation() within the button's click handler. Specifically, include it inside the foo() function for your scenario.

Answer №2

If you want to control the ripple effect in a Material-UI ListItem component, you can utilize the disableRipple property. Simply set it to true when clicking on a button and set it to false when clicking on the list item itself. Here's an example:

const disableRipple = () => this.setState(prevState => ({
  ...prevState,
  parentDisableRipple: true
}));
const enableRipple = () => this.state.parentDisableRipple && this.setState(prevState => ({
  ...prevState,
  parentDisableRipple: false
}));

return (
  <div>
    <Hello name={this.state.name} />
    <p>
      Start editing to see some magic happen :)
    </p>

    <ListItem button={true} 
              disableRipple={this.state.parentDisableRipple}
              onClick={enableRipple()}>
      <Typography variant='caption' color='primary'>
        {value}
      </Typography>
      <Button onClick={foo} >Button</Button>
    </ListItem>
  </div>
);

I've created a playground on STACKBLITZ where you can experiment with this setup.

UPDATE

An alternative solution suggested by @Domino987 involves using onMouseDown along with event.stopPropagation(), as well as wrapping the contents in a <ListItemSecondaryAction> wrapper. You can find more details and examples in this thread.

I have updated my STACKBLITZ to showcase both of these solutions.

Answer №3

<ListItem button={true} matRipple #parent>
 <Typography variant='caption' color='primary' matRipple [matRippleTrigger]="parent"
   [matRippleDisabled]="true">
    {value}
 </Typography>
 <Button onClick={foo}>
    Button
 </Button>
</ListItem>

For a smooth animation effect, make sure to include a template variable for the element you want to animate. Then, activate the parent ripple by setting the [matRippleTrigger] option on the children elements.

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

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

style the table cells based on results of winner values retrieved from JSON

After fetching JSON data, I am utilizing angular JS to present it in a table. The table consists of multiple rows that are populated from the JSON file using ng-repeat. The value for Status.winner can either be 0 or 1. If the winner's value for a p ...

What steps do I need to follow in order to modify a CSS style definition to create a border around

I currently have a CSS style defined as follows: [class*="col-"] { border: 1px solid #dddddd; } This particular CSS definition gives borders to all of the bootstrap grid columns on my page. However, I now want to apply borders only to the bootstrap ...

How can I use jQuery to transform a div with its elements into a canvas?

Looking for a way to convert a HTML Div and its elements to canvas, and then the canvas to an image using Jquery. I've checked out a website that only converts the whole HTML page, but I need a solution for converting specific Div elements. Any help w ...

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

What could be causing my list of files to not properly append to FormData?

I have been working on this issue for the past three days. Despite trying various solutions from different sources, including seeking help from other websites, I am still unable to resolve it. My current challenge involves sending a post request with a Fo ...

Should I use Mongoose schema methods or prototype functions?

I am curious about the functionality of functions and ES6 classes in relation to new objects created from a mongoose schema. I wonder if the functions are duplicated for each new object and what the best approach is when utilizing ES6 classes. To illustrat ...

What is the best way to individually update fields using Prisma?

I am facing a challenge with updating fields individually for an object named Post. This object has three fields: title, content, and summary. Situation To save a post in the database, I can fill in just the title field initially and leave the other fiel ...

What is causing my React project to throw an 'error' event in events.js when I run npm start?

Upon initiating the server for the first time following a code checkout, my React JS project encountered an error stating "events.js:187 throw er; // Unhandled 'error' event". I am using Node 12.13.0 and NPM 6.12.0. You can find the log file atta ...

How to use jQuery to hide radio buttons that are not checked when clicking a submit

Looking to dynamically hide all unchecked radio buttons and their labels until a submit button is clicked, displaying only the checked radio button. <form method="post"> <input type="radio" name="radiobtn"> <label for="first">Fir ...

Is it possible to include a submenu within a md-tooltip?

I have set up an md-tooltip for a sidebar, but I would like to enhance it by enabling a submenu option. For instance, if there is a Contacts submenu under the Profile menu, I want to be able to access Contacts when hovering over the Menu Icon. The tooltip ...

The app I uploaded onto Heroku.com is experiencing technical difficulties and is currently not functioning

After deploying an application on Heroku.com for CI/CD in June, I encountered issues with the link becoming inactive. Click here for image description Despite purchasing a monthly Heroku subscription yesterday, I am still unable to access my application. ...

What are the steps to globalize the ng-bootstrap datepicker?

For my current project, I am utilizing the ng-bootstrap datePicker component. The demo for my simple datePicker widget can be found here. However, I am now seeking to internationalize it by setting it to use the Russian language. Any assistance with this ...

Unable to bring in openai on Node.js

I recently installed Node version 16.13.1 and globally installed the openai package using 'npm install -g openai'. In my script, I imported the necessary packages like this: const { Configuration, OpenAIApi } = require('openai') Howeve ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

onsubmit function was never triggered

Seems like a silly mistake, but I'm encountering an issue with my HTML form. Here's a snippet of the code: <form onsubmit="updateProfile();"> <input type="submit" value="Update Account"> .. ... </form> However, w ...

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

Getting hold of HTML elements in a div on a different page

Recently diving into the world of html/javascript, I find myself engaged in a project where I'm loading an external html page within a div. The loaded content looks like this: <div class="content" id="content"> <object ty ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...