Search code examples
javascriptreactjscode-reuse

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!


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.