Event Handlers
- In react, each element has a property or a prop called
onClick
- event name should be in camelCase
Arrow Function
<ul className="list-group">
{items.map((item) => (
<li className="list-group-item" key={item} onClick={() => console.log("clicked")}>
{item}
</li>
))}
</ul>
Access Parameters
<ul className="list-group">
{items.map((item, index) => (
<li className="list-group-item" key={item} onClick={() => console.log(item, index)}>
{item}
</li>
))}
</ul>
Access Event Parameter
- Arrow function can optionally have a parameter that represent the browser event
- SyntheticBaseEvent is one of the built in classes in React, because different browsers have different implementations of event objects. So to make this cross browser, React team have created a class called synthetic base event that is a wrapper around the native browser event object,
<li className="list-group-item" key={item} onClick={(event) => console.log(item, event)}>
{item}
</li>
Custom Method
If logic gets more complex, we don't want to write that logic here in the middle of a JSX markup. Instead, we should move that logic into a separate function.
Define method
const handleClick = (event: MouseEvent) => console.log(event);
- Specify method
<li className="list-group-item" key={item} onClick={handleClick}>
{item}
</li>
- In Typescript using type annotation, you can specify the type of variable, parameters etc
- With type annotation we get auto completion, type safety, and it's easier to refactor or restructure our code.