Created
March 11, 2022 08:47
-
-
Save kjendrzyca/4accdcb33e708d1073982622b5d1a87d to your computer and use it in GitHub Desktop.
React event handlers naming convention
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// generyczny niebiznesowy komponent | |
export function GenericButton({onClick}) { | |
return ( | |
<button onClick={onClick} /> | |
) | |
} | |
// generyczny niezbiznesowy komponent, gdzie muszę owrapować propsa | |
export function GenericButton({onClick}) { | |
// nie ma większego znaczenia, że się to nazywa "handle*" | |
const handleClick = (event) => { | |
// additional logic | |
onClick() | |
} | |
return ( | |
<button onClick={handleClick} /> | |
) | |
} | |
// biznesowy komponent | |
export function UserProfileContainer() { | |
const saveProfile = () => { | |
fetch.post() | |
} | |
return ( | |
<div> | |
<UserProfile onProfileSave={saveProfile} /> | |
</div> | |
) | |
} | |
export function UserProfile({onProfileSave}) { | |
const validateProfileAndSave = () => { | |
validateProfile() | |
onProfileSave() | |
} | |
return ( | |
<div> | |
<GenericButton onClick={validateProfileAndSave} /> | |
</div> | |
) | |
} | |
// lub | |
export function UserProfile({onProfileSave}) { | |
const handleProfileSave = () => { | |
validateProfile() | |
onProfileSave() | |
} | |
return ( | |
<div> | |
<GenericButton onClick={validateProfileAndSave} /> | |
</div> | |
) | |
} | |
// Ogólna zasada: | |
// Każdy komponent, który umożliwa wykonanie jakiejś dodatkowej funkcji, | |
// powinien nazwać propsa "onSomething", żeby pokazać, "gdzie się można podpiąć" | |
// Czyli jeśli UserProfile, jest odpowiedzialny za zapisanie profilu, bo tam znajduje się przycisk, który to wywoła, | |
// to udostępnia onProfileSave, do którego można się podpiąć. | |
// Nazywanie handlerów "handleSomething" ma sens tylko wtedy, gdy mamy generyczne komponenty, jak jakiś customowy button, | |
// gdzie musimy dodać jakąś dodatkową logikę zanim wywołamy "onClick" przekazany z parenta. | |
// Nazywanie tego "handleClick" ma w tym momencie sens, bo taki handler będzie jeden na cały komponent, | |
// więc nie ma to znaczenia i przez to, jest to po prostu dobra nazwa 🤷♂️. | |
// "handleSomething" może być też dobrą konwencją, gdy nie chcemy nazywać czegoś tak jak ja wyżej "validateProfileAndSave". | |
// Funkcji, które wywołujemy przed wywołaniem przekazanego z góry "onProfileSave" może być więcej niż 2 | |
// i wtedy dopisywanie kolejnych "andSomethingAndSomething" nie ma sensu. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment