Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Handlers in React Stateless Components

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?

like image 732
aStewartDesign Avatar asked Aug 31 '16 23:08

aStewartDesign


People also ask

What are event handlers in React?

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.

How do you call a component onClick in React?

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.

Which component is stateless component in React?

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.


1 Answers

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().

like image 148
Jed Richards Avatar answered Oct 18 '22 16:10

Jed Richards