Refactor a Stateful Toggle Component to a Functional Component with React PowerPlug

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 3 years ago

In this lesson we'll look at React PowerPlug's Toggle component by refactoring a normal class component with state and handlers to a functional component powered by React PowerPlug.

Instructor: [00:00] I have a simple toggle component. I'll be refactoring to use React PowerPlug. This component consists of state, a handle method to toggle the state true or false, and a render method to toggle between the full moon and the new moon emojis.

[00:14] React PowerPlug offers various render less component for common use cases like loaders, lists, and toggles. Let's refactor our example to use the PowerPlug toggle component. First, we'll import the toggle component from React PowerPlug. Since PowerPlug provides the state and logic for us, we'll modify our component to be a functional component instead of a class.

[00:40] Next, we'll wrap it with the new toggle component from React PowerPlug. We'll go ahead and give our initial state, the value of true. This means that our toggle will be ON by default. Something to remember is that, all PowerPlug components expect a render property. Toggle provides four properties for us to utilize in our rendered component ON, OFF, Toggle, and SET ON.

[01:13] The properties ON and OFF are both Booleans. Toggle is a function to toggle between ON and OFF, and SET ON allows you to specifically set the value ON or OFF. One of our main benefits in this solution is that our state and logic are usable, and completely separate from our UI. In other words, we can literally pass anything we want as a render prop and make it a toggle.

[01:35] Let's go ahead and digest that and adjust the render portion of our component and test it out. All right, so it looks like that works. I'm going to change the ternary to ampersands, and show that OFF also works.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today