Khan / react-multi-select

A multiple select component for React
MIT License
183 stars 97 forks source link

Select one value by default #13

Closed backhamza closed 6 years ago

backhamza commented 6 years ago

Hi there,

I want to select one value by default. Below is my code. Please help me it's urgent.

const benefit = [ {label: "High Trust", value: "High Trust"}, {label: "Low Trust", value: "Low Trust"}, {label: "Medium Trust", value: "Medium Trust"} ];

`

  •             <Dropdown
                  options={benefit}
                  onSelectedChanged={this.handleBenefitChanged.bind(this)}
                  selected={this.state.filterValues.Benefits}
                />
              </li>`

    When I did log this this.state.filterValues.Benefits[1] I am getting Low Trust.

  • BrianGenisio commented 6 years ago

    You aren't showing what your full code looks like, but you'll need to initialize your state.filterValues.Benefits with the value you want. You didn't post your state initialization code or your handleBenefitChanged code, so I can't tell exactly what is wrong.

    Also, I see you are using <Dropdown> but shouldn't you be using <MultiSelect>? Or are you just aliasing MultiSelect as Dropdown?

    backhamza commented 6 years ago

    Here is a full code:

    import Dropdown from './dropdowns';
    import MonthPickerSection from './monthPickerSection';
    
    const categories = [
        {label: "Company", value: "Company"},
        {label: "Nutrition", value: "Nutrition"},
        {label: "Product & Brand Generic", value: "Product & Brand Generic"},
        {label: "Quality & safety", value: "Quality & safety"},
        {label: "Social Responsibility", value: "Social Responsibility"}
    ];
    const sub_categories = [
        {label: "Advertising & Communications", value: "Advertising & Communications"},
        {label: "Calendar", value: "Calendar"},
        {label: "Calories", value: "Calories"},
        {label: "Cancer / MOSH", value: "Cancer / MOSH"},
        {label: "Child Labour", value: "Child Labour"},
        {label: "Choking Hazard Ban", value: "Choking Hazard Ban"},
        {label: "Cocoa", value: "Cocoa"},
        {label: "Cooking with Kinder", value: "Cooking with Kinder"},
        {label: "Environment", value: "Environment"},
        {label: "Games", value: "Games"},
        {label: "Gluten Free", value: "Gluten Free"},
        {label: "Health", value: "Health"},
        {label: "History", value: "History"},
        {label: "Honey", value: "Honey"},
        {label: "Ingredients Generic", value: "Ingredients Generic"},
        {label: "Milk", value: "Milk"},
        {label: "Palm Oil", value: "Palm Oil"},
        {label: "Price & Purchase", value: "Price & Purchase"},
        {label: "Product", value: "Product"},
        {label: "Promotions", value: "Promotions"},
        {label: "Purchase", value: "Purchase"},
        {label: "Pure Brand", value: "Pure Brand"},
        {label: "Salt", value: "Salt"},
        {label: "Seasonal", value: "Seasonal"},
        {label: "Sport", value: "Sport"},
        {label: "Sugar", value: "Sugar"},
        {label: "Toys", value: "Toys"}
    ];
    const benefit = [
      {label: "High Trust", value: "High Trust"},
      {label: "Low Trust", value: "Low Trust"},
      {label: "Medium Trust", value: "Medium Trust"}
    ];
    const behaviour = [
      {label: "France", value: "France"},
      {label: "Germany", value: "Germany"},
      {label: "Italy", value: "Italy"},
      {label: "UK", value: "UK"}
    ];
    const brand_type = [
      {label: "Brand", value: "Brand"}
    ];
    
    class Filters extends Component {
      constructor() {
        super();
        this.state = {
          childVisible: false,
          selected: {},
          filterValues: {
            categories: [],
            subCategories: [],
            Benefits: [],
            behavior: [],
            keywordType: []
          }
        }
      }
    
    handleCategoriesChanged(selected) {
      let {filterValues} = this.state;
      filterValues.categories = selected;
      this.setState({
        filterValues
      }, this.props.allDropDownValues(filterValues));
    }
    
    handleSubcategoriesChanged(selected) {
     let {filterValues} = this.state;
     filterValues.subCategories = selected;
      this.setState({
        filterValues
      }, this.props.allDropDownValues(filterValues));
    }
    
    handleBenefitChanged(selected) {
      let {filterValues} = this.state;
      filterValues.Benefits = selected;
         this.setState({
           filterValues
         }, this.props.allDropDownValues(filterValues));
    }
    
    handleBehaviorChanged(selected) {
      let {filterValues} = this.state;
      filterValues.behavior = selected;
      this.setState({
        filterValues
      }, this.props.allDropDownValues(filterValues));
    }
    
    handleKeywordTypeChanged(selected) {
      let {filterValues} = this.state;
      filterValues.keywordType = selected;
      this.setState({
        filterValues
      }, this.props.allDropDownValues(filterValues));
    }
    
      handleSelectedChanged(selected) {
    
      }
    
      handleStartDate(selected) {
        let {filterValues} = this.state;
        filterValues.startDateValue = selected;
        this.setState({
          filterValues
        }, this.props.allDropDownValues(filterValues));
      }
    
      handleEndDate(selected) {
        let {filterValues} = this.state;
        filterValues.endDateValue = selected;
        this.setState({
          filterValues
        }, this.props.allDropDownValues(filterValues));
      }
    
      handlePeriodClick(filterValues) {
        this.setState({
          filterValues
        }, this.props.allDropDownValues(filterValues));
      }
    
      clearFilters() {
        let {filterValues} = this.state
        filterValues.categories = categories.map(category => category.value)
        filterValues.subCategories = sub_categories.map(subCategories => subCategories.value)
        filterValues.Benefits = benefit.map(Benefit => Benefit.value)
        filterValues.behavior = behaviour.map(behavior => behavior.value)
        filterValues.keywordType = brand_type.map(brand_type => brand_type.value)
        this.setState({
          filterValues
        }, this.props.allDropDownValues(filterValues))
      }
    
       render() {
         const selectAll = "Select All"
         return(
           <div className="filters">
             <ul>
               <li>
                 <label>Market</label>
                 <Dropdown
                   options={behaviour}
                   onSelectedChanged={this.handleBehaviorChanged.bind(this)}
                   selected={this.state.filterValues.behavior}
                 />
               </li>
               <li>
                 <label>Macro Topic</label>
                 <Dropdown
                   options={categories}
                   onSelectedChanged={this.handleCategoriesChanged.bind(this)}
                   selected={this.state.filterValues.categories}
                 />
                 </li>
                 <li>
                   <label>Micro Topic</label>
                   <Dropdown
                     options={sub_categories}
                     onSelectedChanged={this.handleSubcategoriesChanged.bind(this)}
                     selected={this.state.filterValues.subCategories}
                   />
                  </li>
                  <li>
                    <label>Trust Level</label>
                    <Dropdown
                      options={benefit}
                      onSelectedChanged={this.handleBenefitChanged.bind(this)}
                      selected={this.state.filterValues.Benefits}
                    />
                  </li>
                  <li>
                    <label>Keyword Type</label>
                    <Dropdown
                      options={brand_type}
                      onSelectedChanged={this.handleKeywordTypeChanged.bind(this)}
                      selected={this.state.filterValues.keywordType}
                    />
                  </li>
                  <li className="monthSelection">
                    <label>Month</label>
                    <div onClick={() => this.onClick()} className="monthSelected"><span>Select Period</span></div>
                    {
                      this.state.childVisible
                      ? <MonthPickerSection
                          startDate={this.handleStartDate.bind(this)}
                          endDate={this.handleEndDate.bind(this)}
                          allDropDownValues={this.handlePeriodClick.bind(this)}
                        /> : null
                    }
                  </li>
                  <li>
                    <span className="btn" onClick={this.clearFilters.bind(this)}>
                      <i className="fa fa-trash" aria-hidden="true"></i>&nbsp; Clear Selection
                    </span>
                  </li>
             </ul>
           </div>
         );
       }
    
       componentDidMount () {
         let {filterValues} = this.state
         filterValues.categories = categories.map(category => category.value)
         filterValues.subCategories = sub_categories.map(subCategories => subCategories.value)
         filterValues.Benefits = benefit.map(Benefit => Benefit.value)
         filterValues.behavior = behaviour.map(behavior => behavior.value)
         filterValues.keywordType = brand_type.map(brand_type => brand_type.value)
    
         this.setState({
           filterValues
         })
    
       }
    
       onClick() {
         this.setState({childVisible: !this.state.childVisible});
      }
    };
    export default Filters;

    Dropdown.js

    import MultiSelect from '@khanacademy/react-multi-select';
    import '../node_modules/@khanacademy/react-multi-select/dist/select-item.js';
    
    class Dropdown extends Component {
        constructor(props) {
            super();
            this.state = {
                selected: props.selected || [],
            };
        }
    
        props: {
            options: Option[],
            valueRenderer?: (values: Array<any>, options: Array<Option>) => string,
            ItemRenderer?: Function,
            selectAllLabel?: string,
            isLoading?: boolean,
        }
    
        handleSelectedChanged(selected) {
            this.setState({selected}, this.props.onSelectedChanged(selected));
        }
    
        render() {
            const {
                ItemRenderer,
                options,
                selectAllLabel,
                valueRenderer,
                isLoading,
            } = this.props;
            const {selected} = this.state;
    
            return <div>
                <MultiSelect
                    options={options}
                    onSelectedChanged={this.handleSelectedChanged.bind(this)}
                    selected={selected}
                    valueRenderer={valueRenderer}
                    ItemRenderer={ItemRenderer}
                    selectAllLabel={selectAllLabel}
                    isLoading={isLoading}
                />
            {/* <h2>Selected:</h2>
            {selected.join(', ')} */}
            </div>;
        }
    
        componentDidMount () {
          let defaultSelected = this.props.selected || []
          this.setState({
            selected: defaultSelected
          })
        }
    
        componentWillReceiveProps (nextProps) {
          let defaultSelected = nextProps.selected || []
          this.setState({
            selected: defaultSelected
          })
        }
    }
    
    export default Dropdown;

    Yes. For your 2nd question.

    BrianGenisio commented 6 years ago

    I imported your code into a create-react-app shell, and it all seems to be working as I expected it would. Here is a quick screenshot... what about this behavior is not working as you would expect?

    filters

    backhamza commented 6 years ago

    Hey, Thanks @BrianGenisio for your help. This is not the problem I was looking for. Anyways I solve it my self.