Lets start with the basics and just build the API first. For the icon we’re going to use one of the icons from material ui components library. Hopefully, it will be obvious which one is better in the end. Or, to be precise, let’s build three buttons, with 3 different APIs for passing the icon, and then compare them. Let’s see how it can be done with the three patterns we identified at the beginning: Instead of passing to the Button the detailed limited description of the Icon in form of its name and its props, our Button can just say: "gimme an Icon, I don't care which one, your choice, and I'll render it in the right place". This is where passing components in props come in handy. We also forced our Button component to know about every icon it can render, which means the bundled js of this Button will not only include its own code, but also every single icon on the list. It’s not only a very limited and complicated API. I’m not even going to implement it here, it’d be way too complicated: we’d have to expose onHover callback, introduce state management in every single parent component, set state when the button is hovered, etc, etc. What about giving people the ability to change the icon when something in the button changes? If a button is hovered, for example, and I want to change icon’s color to something different. We could, of course, implement it like this: Imagine, for example, we’re implementing a button with an icon. Short answer: for flexibility and to simplify sharing data between those components. There is a definitive answer to those questions □ Why would we want to pass components as props?īefore jumping into coding, let’s first understand why we would want to pass components as props to begin with. Or, if you like spoilers, just scroll to the summary part of the article. So which way is the best way and which one should be avoided? Which one should be included in some “React best practices” list and why? Let’s figure it out together! I can pass them as functions like Material UI Data Grid component does with its renderCell prop.I can pass them as components themselves like for example react-select library does for its components prop.I can pass them as Elements like Material UI library does in Buttons with the startIcon prop.If, for example, I need to pass a component as a prop to another component, how should I do this? If I search the popular open-source libraries for an answer, I will find that: As always in React, there is one million way to do exactly the same thing.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |