Adding Intractability to React

Context:

When an emoji is chosen, it must be set to the user dynamically. Because it needs to be dynamic, we need to hook into the React lifecycle so that whenever there’s a change it can be updated automatically.

My class structure:

Menu - generic
        MenuItem - generic
EmojiMenu extends Menu
        EmojiMenuItem extends MenuItem

Problem 1 - Whose State? :

Whose state should be changed?
EmojiMenu (parent) or EmojiMenuItem (child)?
Initially I thought it should be EmojiMenuItem’s state ( a bool, isChosen ) so that it can manage its own resources. To change its state from within the it’s parent’s method you need to use refs.

Solution 1 - It should be Parent’s State:

After reading this React Doc - More About Refs

“If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy . Placing the state there often eliminates any desire to use refs to "make things happen" – instead, the data flow will usually accomplish your goal.”

I realized that my initial choice was probably the wrong one. I could easily set the state for the parent ( theChosenEmoji : “nameOfChosenEmoji” ), simplifying the code.

Problem 2 and Solution 2 - Use refs this time:

Now I also wanted to add the attribute aria-checked to each EmojiMenuItem for accessiblity. In this case, it was clear that refs need to be used because aria-checked is an attribute EmojiMenuItem tag.

In my render() function:




In my click handler:


Comments

Popular Posts