Home > Blockchain >  React props reusability
React props reusability

Time:12-01

I currently have a piece of code like this:

    return (
        creatable
        ? <Select
            options={options}
            value={value}
            onChange={(selectedValue) => valueSetter(selectedValue)}
        />
        : <CreatableSelect
            options={options}
            value={value}
            onChange={(selectedValue) => valueSetter(selectedValue)}
        />
    )

As you can see, both of the components accept the exact same props. Is there any way that I can increase code reusability in this code (something like putting the props into a dictionary and unpack them)?

Thank you!

CodePudding user response:

Yes, you can easily achieve this via the spread syntax.

Should look like this:

const props = {
   options,
   value,
   onChange: (selectedValue) => valueSetter(selectedValue)
}

return (
   creatable
      ? <Select {...props} />
      : <CreatableSelect {...props} />
)

What we do here is "spread" the content of a dedicated props object we've created and pass it to the target components.

CodePudding user response:

The @tomled answer is good. but we do not need redefine onChange function.

const props = {
   options,
   value,
   onChange: valueSetter
}

return (
   creatable
      ? <Select {...props} />
      : <CreatableSelect {...props} />
)
  • Related