Debounce and avoid multiple clicks event generation on React.js…
There are some instances where you need to debounce and avoid multiple clicks/taps on a button so that it will not generate the same action chain immediately with a consecutive click. An example would be an application with a touchscreen. If you click a button rapidly, that event will be generated more than once. As a solution, most of the time devs would block the UI until the action chain is completed. But this would be a bad experience if the user is blocked for any other interactions. A typical example can be a fetch call to update the state and if the invocation is asynchronous it could be causing more inconvenience.
How to debounce and avoid multiple clicks
What I did was to create a stateful component with react.js and use debounce
function of Lodash(https://lodash.com/docs/4.17.4#debounce). This will debounce and avoid multiple clicks which are generated after the first click/tap for a limited time. With leading: true, it will define that the first click will be executed all the trailing invocations are discarded.
I created a ClickableComponent
class which could be used for any component with an onClick
parameter.
class ClickableElement extends React.Component { static INTERVAL = 1000; constructor(props) { super(props); this.state = {}; } componentWillReceiveProps(nextProps) { const { onClick, disabled } = nextProps; this.setState({ onClick, disabled, }); } onClickDebounced(e) { const { onClick, disabled } = this.state; if (!disabled && _.isFunction(onClick)) { onClick(e); } } componentWillMount() { this.componentWillReceiveProps(this.props); const { clickWait } = this.props; const wait = clickWait || Button.INTERVAL; this.onElementClicked = _.debounce(this.onClickDebounced, wait, { maxWait:wait, leading: true, trailing: false, }); } }
Note that I have used Lodash as _
in the code. Now you can use it in any component where you would invoke onClick
function.
export class TouchButton extends ClickableElement { render() { const otherProps = _.omit(this.props, ['onClick', 'type']); return ( <button onClick={e => this.onElementClicked(e)} type="button" {...otherProps} >{otherProps.value}</button> ); } }
See the Pen React Debounce Button by Sandaruwan Nanayakkara (@sandaruny) on CodePen.
Finally the click debouncing time is in milliseconds and default wait time of one second has set with INTERVAL
static property. And if you want to override the waiting time for the clicks, you can set the wait
time as desired.
<TouchButton clickWait={2000} onClick={() => doSomething()} value="Something" />
This is working great and if you want to generate an event for once, you can slightly modify the Lodash debounce function parameters.
If you have simpler approach please do give a feedback.
35 COMMENTS
Hi! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the excellent work!
We will teach you how to earn $ 7000 per hour. Why?
We will profit from your profit.https://go.binaryoption.ae/FmUKhe
Your article has answered the question I was wondering about! I would like to write a thesis on this subject, but I would like you to give your opinion once 😀 casinosite
About half of these women experience hot flushes cialis generic reviews
This is a fantastic article that provides practical tips and advice for readers. Your writing style is engaging and the information is presented in a way that is easy to understand and apply.
Your article is informative and well-researched. I learned a lot from reading it and appreciate the effort you put into creating such a valuable resource.
I am very impressed with the knowledge and research you put into writing this article.
sexualcase
This article has been very beneficial and informative to me.
I simply couldn’t leave your web site before suggesting that I
actually loved the standardd information an individual supply in your visitors?
Is gonna be again incessantly too investigate cross-check neww posts
Visit my webpage – Slot Online
I was suggested this website by my cousin. I am not sure whether
this post is written by him as no one else
know such detailed about my problem. You’re wonderful!
Thanks!
Feel free to visit my blog post; jdb
[url=https://tepliciveka.ru]Теплицу.[/url]
Your article is an excellent starting point for anyone interested in learning more about the topic.
Your writing is so relatable and down-to-earth. It feels like you’re speaking directly to me and my experiences.
I love how you present the information in an easy to understand way.
I’m always impressed by the level of research and detail you put into your articles. It shows how committed you are to providing high-quality content.
Thanks for sharing your insights on this topic. It’s always great to hear different perspectives.
Your article is very informative and provides practical solutions to the problem. Thank you for sharing your expertise.
I like the way you present information with solid data and facts.
I appreciate the thoroughness of your article. You covered all aspects of the topic in a comprehensive and engaging way.
Your writing style is so engaging and relatable. It feels like I’m having a conversation with a friend, rather than reading an article.
Here are more donkeys in the making.In 2016, 3 idiots from JNTU wrote one of the stupidest papers I have read. This is as awful as Kannan’s stupid paper.Puratana Aakasha-Yantrika Nirmana Sadhanavasthu (Ancient Aero-mechanical manufacturing materials)https://www.sciencedirect.com/science/article/pii/S2214785317314001The paper is now retracted and people were asking Science Direct/Elsevier how they could be so stupid. Goes to show how bad science publishing has become. It is like peer review is completely missing. Elsevier is a major publisher, but developed bad reputation for promoting bad science and bad journals, for some time now.Now this main author, Eshwar Reddy Cholleti is a PhD candidate in University of Auckland, New Zealand. He will no doubt come out with a PhD and continue to be a donkey. You can’t fix stupid at this level. Also, are Australian and New Zealand universities so bad now at selecting PhD students?Second author Kavya Vaddadi was already a member of stupid science groups such as SWASTIK and Vedic Scientific Research Foundation and now calls herself Researcher on Ancient Advanced space science and Technology.Third author looks like a jobless private tutor now and does not seem to have ability to construct sentences.Expect these donkeys to embarrass India one more time in a few years. More Hegdes in the making. Reserve Padma Bhushans for them.
Your comprehensive article is an excellent resource for anyone looking to deepen their understanding of the topic.
This article is a great example of how to write a persuasive argument. You presented your points clearly and effectively.
This is my first time pay a quick visit at here and i am really happy to read everthing at one place
Great blog here! Also your website loads up fast! What web host are you using?
Can I get your affiliate link to your host? I wish my
website loaded up as quickly as yours lol
I pay a quick visit each day a few websites and blogs to read articles or reviews, except this blog presents quality based articles.
May I request that you elaborate on that? Your posts have been extremely helpful to me. Thank you!
Забота о жилище – это забота о радости. Термомодернизация фасадов – это не только модный облик, но и обеспечение тепла в вашем уголке уюта. Профессионалы, группа специалистов, предлагаем вам сделать ваш дом в прекрасное место обитания.
Наши дизайнерские решения – это не просто утепление, это искусство с каждым слоем. Мы предпочитаем идеальному балансу между эстетикой и функциональностью, чтобы ваш дом преобразился не только теплым, но и привлекательным.
И самое важное – удовлетворительная стоимость! Мы верим, что профессиональные услуги не должны быть неподъемными по цене. [url=https://ppu-prof.ru/]Стоимость работ по утеплению фасада[/url] начинается всего начиная с 1250 руб/м².
Применение современных технологий и материалов высокого качества позволяют нам создавать термомодернизацию, которая гарантирует долгий срок службы и надежность. Забвение о холодных стенах и избежание лишних расходов на отопление – наше утепление станет вашим надежной защитой от холода.
Подробнее на [url=https://ppu-prof.ru/]https://ppu-prof.ru[/url]
Не откладывайте на потом заботу о удовольствии в вашем доме. Обращайтесь к опытным строителям, и ваш дом преобразится настоящим творческим шедевром, которое согреет вас не только теплом. Вместе мы создадим обители, где вам будет по-настоящему комфортно!
I am really impressed with your writing skills as well as with the layout on your weblog.
Is this a paid theme or did you modify it yourself?
Either way keep up the nice quality writing, it is rare to see a nice blog like
this one nowadays.
This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!
What makes Sumatra Slim Belly Tonic even more unique is its inspiration from the beautiful Indonesian island of Sumatra. This supplement incorporates ingredients that are indigenous to this stunning island, including the exotic blue spirulina. How amazing is that? By harnessing the power of these rare and natural ingredients, Sumatra Slim Belly Tonic provides you with a weight loss solution that is both effective and enchanting.
Your article provides a unique perspective on this topic
Your article was an excellent resource for anyone looking to learn more about this subject. Thank you for sharing your expertise.
When I initially left a comment I seem to have clicked
on the -Notify me when new comments are added- checkbox and
from now on every time a comment is added I recieve four emails
with the exact same comment. Is there a way you can remove me from that service?
Thank you!