Reputation: 59
I have to use multiple dropdowns from semantic-ui-react in my project. They need to have different props. It looks like this
<div className="wrapper">
<img className="icon" src={iconA} alt="iconA"></img>
<h1>A</h1>
<Dropdown
className="dropdown"
search
selection
options={optionsA}
placeholder="A"
defaultValue="A"
onChange={handleAChange}
/>
</div>
<div className="wrapper">
<img className="icon" src={iconB} alt="iconB"></img>
<h1>B</h1>
<Dropdown
className="dropdown"
search
selection
options={optionsB}
placeholder="B"
defaultValue="B"
onChange={handleBChange}
/>
</div>
I want to refactor this and create a single component for this by pasing different props. Please guide me on how this can be refactored in the best way possible.
Upvotes: 0
Views: 119
Reputation: 80
First, create your custom dropDown component and extract props using object destructuring, you can give deafult values to props there itself, but better use PropTypes for that.
const CustomDropDown = (props) => {
const {
className,
search,
selection,
options,
placeholder,
defaultValue,
onChange
} = props;
return (
<div className="wrapper">
<img className="icon" src={iconA} alt="iconA"></img>
<h1>A</h1>
<Dropdown
className={classname}
search={search}
selection={selection}
options={optionsA}
placeholder={placeholder}
defaultValue={defaultValue}
onChange={onChange}
/>
</div>
)
}
Now, call the component like this,
<CustomDropDown
className="dropdown"
search
selection
options={optionsA}
placeholder="A"
defaultValue="A"
onChange={handleAChange}
/>
Upvotes: 1
Reputation: 583
You can do it as follows:
const DropDownWraper = ({
header,
options,
onChange,
iconProps,
placeholde,
defaultValue
}) =>
<div className="wrapper">
<img
className="icon"
src={ iconProps.src }
alt={ iconProps.alt } />
<h1>{ header }</h1>
<Dropdown
search
selection
options={ options }
className="dropdown"
onChange={ onChange }
placeholder={ placeholde }
defaultValue={ defaultValue } />
</div>
Upvotes: 0