React Tips: 5 - Raising Events

March 07, 2020

Raising an Event is an interesting concept is React: essentially, you pass a function into a component; and then, when the component handles an event, it simply calls the function handler. This is referred to as “Raising” the event, because despite the event happening in the component, it is dealt with by a parent of that component. In C#, you would refer to this as a delegate, and in C, this would be passing a pointer to a function.

Here’s a component:



function MyComponent(props) {
    
    return (
        <div>
            <label>Change the text below</label>
            <input type='text' onChange={props.onChange} />
        </div>
    );
}
export default MyComponent;

If you look at that code, you’ll see that the onChange event is handled by a function passed in, called onChange. Here’s the calling component:



export class Home extends Component {

  render () {
    return (
      <div>
        <MyComponent onChange={this.onChange} />
      </div>
    }

The onChange function in Home will be called whenever the MyComponent textbox is changed.

Important Note

Since this is React, one of the things that you may do in the onChange function is to update the state. I have previously written on how to deal with this, or indeed any method which uses the this property.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024