Forward Advance Learning

Making Components Emit Events

We can think of Components as being like new DOM nodes that we define. DOM nodes have input and output.

Here is a regular old anchor tag:

<a href="cats" onclick="miow">Miffy</a>

The input to this is the href property. The output is the onclick event. Both href and onclick are properties of the DOM node.

We can do the same with our own Components.

<Cat onMiow="miow" />

If we pass in a function as a prop and bind it to the parent, then the child component can call a method on the parent.

Here's an example. The App component holds a hero, then the two stateless components simply render him. The App component passes a method to the Arena to allow the hero to take damage.

Data flows down the tree, and children can call methods on their parents to flow it back up again.

Note that these aren't real DOM events. They don't bubble. We're just calling a method in the context of the parent.

See the Pen React Events demo by Nicholas Johnson (@superluminary) on CodePen.

Exercise

Revisit MyFace.com. Try to make it so that Davros can like and unlike his friends.

Extension. Let Davros remove items from his newsfeed.

See the Pen React Vanilla Props One-Way-Binding Demo by Nicholas Johnson (@superluminary) on CodePen.