ihatepineapple
ihatepineapple

Reputation: 65

Dropdown menu in React, filter through list

I am building a rest countries app in react and I'm trying to filter by region through a list. I would like to use a dropdown menu. I have tried using react select, creating a new component, this is my code

const DropdownMenu = (props) => {
    const options = [
        '', 'Africa', 'America', 'Asia', 'Europe', 'Oceania'
      ];
    const defaultOption = options[0];

    const handleFilterInput = (event) => {
        let value = event.target.options;
        props.handleRegionSearch(value);  
    };

    return(
        <div>
            <Select options={options} onChange={handleFilterInput} value={defaultOption} placeholder="Select a region"/>
        </div>
    )
}

export default DropdownMenu;

My problem is, I can not get the value to change to the option selected, therefore it's impossible for me to filter the list I took from the api. Does anyone have a possible solution for this? Thanks

Upvotes: 0

Views: 5715

Answers (2)

ihatepineapple
ihatepineapple

Reputation: 65

Thanks! In the end, I used a react-select component which did solve a this issue on it's own.

Upvotes: 0

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

You are setting the value wrong

value={defaultOption}

This default option is never changing.

What you can do is catch the current value from onChange() and set the value somewhere (preferably in state) and then use that stored value as the value of dropdown component

Something like this.

    const options = [
        '', 'Africa', 'America', 'Asia', 'Europe', 'Oceania'
      ];

    const [selectedValue , setSelectedValue ] = useState(options[0]);

    const handleFilterInput = (event) => {
        let value = event.target.options;
        setSelectedValue(value);
        props.handleRegionSearch(value);  
    };

    return(
        <div>
            <Select options={options} onChange={handleFilterInput} value={selectedValue} placeholder="Select a region"/>
        </div>
    )

Upvotes: 1

Related Questions