Apr '24 (edited) β€’ General discussion
πŸš€ React Tip: Naming Event Handler Props
Hey everyone! Today, let's talk about a neat convention recommended by React when passing functions as props. It's a small detail but can make your code much more intuitive and easier to understand.
Convention:
When you pass a function as a prop in React, it's suggested to name it in the format on{actionName}. This convention provides clarity and consistency, making it easier for others (and your future self!) to understand your code at a glance.
Example:
Let's say you have a component with a toggle functionality. Instead of naming your function prop something like handleToggle, follow the convention and name it onToggle. Here's how you can implement it:
function ToggleButton({ onToggle }) {
const [isToggled, setIsToggled] = useState(false);
const handleClick = () => {
setIsToggled(!isToggled);
// Call the passed prop function
onToggle();
};
return (
<button onClick={handleClick}>
{isToggled ? 'On' : 'Off'}
</button>
);
}
Usage:
Now, when you use this ToggleButton component, it's clear what the onToggle prop does:
import React from 'react';
import ToggleButton from './ToggleButton';
function App() {
const handleToggle = () => {
console.log('Toggle button clicked!');
// Additional logic here if needed
};
return (
<div>
<h1>Toggle Button Example</h1>
<ToggleButton onToggle={handleToggle} />
</div>
);
}
export default App;
Benefits:
  1. Readability: The naming convention makes it instantly clear that onToggle is an event handler for the toggle action.
  2. Consistency: Following conventions helps maintain consistency across your codebase, making it easier for you and your team to collaborate.
6
0 comments
Basil Gubara
5
πŸš€ React Tip: Naming Event Handler Props
Developer Pro
skool.com/developerpro
Learn how to code. Make money. Have fun. Enjoy life.
Powered by