React: Suggestion: Alias components

Created on 25 May 2020  路  2Comments  路  Source: facebook/react

In our project, we often create components whose purpose is to constrain or enhance another component. We've run into a problem with this approach when a component needs to change how it's displayed based on some state.

For example, suppose we have an IconButton for a button that just contains an icon, and an ActionButton for one that shows text and an icon, and we want to switch a button between these two based on some state. Even though they both render a Button, React sees these as different components and re-creates the button itself when changing between them. If the button was in focus, it will lose focus from this state change.

My idea to solve this problem is to allow components to declare themselves an alias or wrapper for another component. During React's reconciliation, when comparing component types, components will match if they or any of their aliases match. Taking the example above, here's how the reconciliation will work:

Existing component | New component | Matches as
-- | -- | --
IconButton | IconButton | IconButton
ActionButton| ActionButton | ActionButton
IconButton | ActionButton | Button
ActionButton | IconButton | Button
Button | (Icon/Action)Button | Button
(Icon/Action)Button | Button | Button

To ensure that React will always be able to match components like this, a component that declares itself an alias must always return a single element of its aliased component (or null); otherwise React will report an error.

Most helpful comment

Thanks for the response. I've put a lot more thought and details into a full RFC: https://github.com/reactjs/rfcs/pull/167

All 2 comments

This looks like a substantial change being proposed. :smile: Changes like this should go through our RFC process:
https://github.com/reactjs/rfcs#react-rfcs

The RFC process is a great opportunity to get more eyeballs on your proposal before it becomes a part of a released version of React. Quite often, even proposals that seem "obvious" can be significantly improved once a wider group of interested people have a chance to weigh in.

The RFC process can also be helpful to encourage discussions about a proposed feature as it is being designed, and incorporate important constraints into the design while it's easier to change, before the design has been fully implemented.

I am going to close this issue. Please follow the RFC process instead!

Thanks for the response. I've put a lot more thought and details into a full RFC: https://github.com/reactjs/rfcs/pull/167

Was this page helpful?
0 / 5 - 0 ratings