Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React props reusability

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading