简体   繁体   中英

How to create separate DropdownIndicator component using React-select so that it can be reused in other part of the project

The below code works fine when I keep the DropdownIndicator component in the same file.

But I want to keep DropdownIndicator in separate file so that it can be reused. Like keep it separate component and use it in other files like wherever required in dropdown fields to show the caret up and down icon.

similar example like below

import ReactDOM from "react-dom";
import Select, { components } from "react-select";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCaretDown, faCaretUp } from "@fortawesome/free-solid-svg-icons";
import { library } from "@fortawesome/fontawesome-svg-core";
import "./styles.css";

library.add(faCaretDown);
library.add(faCaretUp);

const colourOptions = [
  {
    label: "Orange",
    value: "orange"
  },
  {
    label: "Blue",
    value: "blue"
  },
  {
    label: "Purple",
    value: "purple"
  }
];

const Placeholder = (props) => {
  return <components.Placeholder {...props} />;
};
let isOpen = false;
const CaretDownIcon = () => {
  return <FontAwesomeIcon icon="caret-down" />;
};

const CaretUpIcon = () => {
  return <FontAwesomeIcon icon="caret-up" />;
};

const DropdownIndicator = (props) => {
  return (
    <components.DropdownIndicator {...props}>
      {isOpen ? <CaretDownIcon /> : <CaretUpIcon />}
    </components.DropdownIndicator>
  );
};

function App() {
  return (
    <div className="App">
      <Select
        closeMenuOnSelect={false}
        onMenuOpen={() => (isOpen = true)}
        onMenuClose={() => (isOpen = false)}
        components={{ Placeholder, DropdownIndicator }}
        placeholder={"Choose"}
        styles={{
          placeholder: (base) => ({
            ...base,
            fontSize: "1em",
            color: colourOptions[2].value,
            fontWeight: 400
          })
        }}
        options={colourOptions}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

First of all, the way you're holding the isOpen flag is not ideal as it would make the indicators change for all present Selects.

To extract the component you could leverage the select props passed to the custom DropdownIndicator and use that instead of your flag.

Here's a working sandbox:

https://codesandbox.io/s/custom-dropdown-indicator-5shel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM