https://facebook.github.io/react/docs/thinking-in-react.html

So I have been studying ReactJS that last couple weeks. Mostly banging my head trying to come up with simple examples. Here is one based on Thinking in React that demos how to do callbacks.

Starting simple

Here is a simple bit of code that counts words.

Screen Shot 2017-09-01 at 8.44.25 AM.png

Note the main component is called ‘WordCount’, and it does a fine job of counting words.

Adding composition and parent callbacks

But what I want to do is create a sub-component, maintain the state in the parent component, and have the parent component pass it’s callback down to the subcomponent so it can be called back.

Here is what I got working.

Screen Shot 2017-09-01 at 8.47.15 AM.png

Note the following.

  1. Child calls parent callback

I don’t know if this is common, or even necessary, but based on the Thinking in React example this is what they do.

You define your parent callback like so

Screen Shot 2017-09-01 at 8.49.31 AM.png

And then you pass it to your child like so:

Screen Shot 2017-09-01 at 8.50.04 AM.png

Note the name pattern. ‘onSomething’ ‘handleSomething’. This I have seen in many examples and this seems common.

But then in the child you define another similar callback, and have it do nothing more than prep the data and call the parent.

Screen Shot 2017-09-01 at 8.51.20 AM.png

I don’t know what you would do this. I guess if you wanted to do some more processing (you know the saying about always adding another layer of indirection).

And then you use this child callback locally which in turn calls the parent callback we just defined.

Screen Shot 2017-09-01 at 8.53.06 AM.png

This works. I am just not sure if it’s right or needed.

What I would have expected to be able to do, is just pass the parent callback directly to the child component itself.

But I haven’t been able to figure out how to do that yet. Stay tuned…

Advertisements