Home > Enterprise >  Can i extract props object destruction into module?
Can i extract props object destruction into module?

Time:12-28

My case: I have two react components with 90% identical props data, but different HTML.

I don't want to double variables declaration into two files.

So I want to export the main part of props destruction into an importable object or something. Is exist any way to do this? Or maybe a different way to do this?

function ProductTotalCount (props) {
    //common part it's doubled in two files
    const {
        className,
        activeClassName,
        big,
        cleared,
        totalCount,
        max,
        min,
        changedManually,
        deviceType,
        cities,
        updateData
    } = props
  
  // specific props for component
  const { setSelectedCityDropdownOpen } = props  
  
  //next part of component
  

CodePudding user response:

I'd suggest you to implement reusable, stateless UI components like a

  • dropdown list with a selected prop and data prop and onSelect prop instead of setSelectedCityDropdownOpen and cities
  • other UI elements which can display any text (instead of hardcode an elem dedicated for totalCount for example)

These stateless UI components can be used for anything not only for cities.

Then wrap them into a parent component (container) which introduces all the use-case specific logics like currently selected city, min, max value, totalCount etc as a state (its name can be e.g. CitySelector which is very use-case specific).

This parent should handle all logics and pass the values stored in their state down to the reusable UI components.

CodePudding user response:

There are two assumptions that I am taking:

  1. Since you are having 90% of the same props, is the jsx same for those common props only and not the whole component. If yes, then you can create a common component for common props only and use them in both of your other components.

  2. If first is not the case, then to be honest if you really want to use destructuration in order to use variables, in that case I don't think you can do much about it, but yeah you can separate keys with different names from the ones that are common using:

{ setSelectedCityDropdownOpen, ...rest } = props;

in this, rest will contain all your common props, and then you can use them as rest[key].

  • Related