Trying to figure out an optimal way to create event handlers in React stateless components. I could do something like this:
const myComponent = (props) => { const myHandler = (e) => props.dispatch(something()); return ( <button onClick={myHandler}>Click Me</button> ); }
The drawback here being that every time this component is rendered, a new "myHandler" function is created. Is there a better way to create event handlers in stateless components that can still access the component properties?
What are event handlers in React? Event handlers determine what action is to be taken whenever an event is fired. This could be a button click or a change in a text input. Essentially, event handlers are what make it possible for users to interact with your React app.
We use props to determine the function that gets called when the onClick event fires, and the text within the button. We do this also for the ListComponent's inner text. import { Button } from './Button. js'; import { ListComponent } from './ListComponent.
Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.
Applying handlers to elements in function components should generally just look like this:
const f = props => <button onClick={props.onClick}></button>
If you need to do anything much more complex it's a sign that either a) the component shouldn't be stateless (use a class, or hooks), or b) you should be creating the handler in an outer stateful container component.
As an aside, and undermining my first point slightly, unless the component is in a particularly intensively re-rendered part of the app there's no need to worry about creating arrow functions in render()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With