React-select - Replacing Components For Custom Option Content
Solution 1:
For a majority of use cases, you probably don't need to replace the full Option component. If you're looking to stay with the same overall structure and look and feel of the Option, but you want to display several blocks of text, or an image, or some other special treatment to the body of each option, there is an easier way.
That's to use the formatOptionLabel
render prop.
importReactfrom"react";
importReactDOM from"react-dom";
importSelectfrom"react-select";
const options = [
{ value: "Abe", label: "Abe", customAbbreviation: "A" },
{ value: "John", label: "John", customAbbreviation: "J" },
{ value: "Dustin", label: "Dustin", customAbbreviation: "D" }
];
constformatOptionLabel = ({ value, label, customAbbreviation }) => (
<divstyle={{display: "flex" }}><div>{label}</div><divstyle={{marginLeft: "10px", color: "#ccc" }}>
{customAbbreviation}
</div></div>
);
constCustomControl = () => (
<SelectdefaultValue={options[0]}formatOptionLabel={formatOptionLabel}options={options}
/>
);
ReactDOM.render(<CustomControl />, document.getElementById("root"));
https://codesandbox.io/embed/reactselect-formatoptionlabel-bde1q
https://react-select.com/props - search for formatOptionLabel
Solution 2:
You can replace any component by including your override in the components property.
<Selectcomponents={{Option:MyOption}} />
Something like:
constMyOption = props => {
const { innerProps, innerRef } = props;
return (
<articleref={innerRef} {...innerProps} className="custom-option"><h4>{props.data.artist}</h4><divclassName="sub">{props.data.title} </div></article>
);
};
<Selectcomponents={{Option:MyOption}} />
The innerRef
and innerProps
properties are very important, as they carry forward things like the hover and onClick needed by the Option. The data
in props is where your option data is.
Solution 3:
Generally, you indeed want to use formatOptionLabel
prop (no extra component). But in case you don't, you may override the Option
component this way:
importSelect, { components } from'react-select';
constCustomOption = ({ children, ...props }) => {
return (
<components.Option {...props}><imgsrc={...} />
{children}
</components.Option>
);
};
functionApp() {
return (
<Selectcomponents={{Option:CustomOption}} ... />
);
}
Here I reuse the stock component (components.Option
). This way I don't need to care about innerRef
or something.
Solution 4:
If you want to style your option when it has been selected you can use a custom option like so:
constcustomOption = (props) => (
{props.isSelected ? (
<imgclassName="custom-option__img"src={IconCheck}alt="" />
) : (
''
)}
);
Post a Comment for "React-select - Replacing Components For Custom Option Content"