Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
eventsdomclean-codereactaccessibility

Avoid redundant preventDefault

Do not use event.preventDefault() if declarative HTML attributes like readOnly or disabled already enforce the desired behavior.

PR: Fix/FCK-2261 - Fix issues with the Kapital frontpage widget #4151Created: Dec 7, 2025

Bad example

Old codetsx
1const handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
2 // Redundant: readOnly already prevents modification
3 event.preventDefault();
4 openModal();
5};
6
7return <input readOnly value="Search..." onFocus={handleFocus} />;

Explanation (EN)

Using preventDefault() here is unnecessary because the 'readOnly' attribute already prevents the user from modifying the value. It adds noise and suggests special handling that isn't actually occurring.

Objašnjenje (HR)

Korištenje preventDefault() ovdje je nepotrebno jer atribut 'readOnly' već sprječava korisnika da mijenja vrijednost. To dodaje šum u kod i sugerira posebno rukovanje koje se zapravo ne događa.

Good example

New codetsx
1const handleFocus = () => {
2 // Rely on the standard browser behavior for readOnly inputs
3 openModal();
4};
5
6return <input readOnly value="Search..." onFocus={handleFocus} />;

Explanation (EN)

We rely on the declarative 'readOnly' attribute to enforce non-editability. The event handler focuses solely on the side effect (opening the modal) without interfering with standard browser events.

Objašnjenje (HR)

Oslanjamo se na deklarativni atribut 'readOnly' kako bismo onemogućili uređivanje. Event handler se fokusira isključivo na popratni efekt (otvaranje modala) bez ometanja standardnih događaja preglednika.

Notes (EN)

If the intent is to create a button that looks like an input, consider using a semantic <button> styled as an input instead to ensure better accessibility and event handling.

Bilješke (HR)

Ako je cilj stvoriti gumb koji izgleda kao input, razmislite o korištenju semantičkog <button> elementa stiliziranog kao input radi bolje pristupačnosti i rukovanja događajima.