azr481
azr481

Reputation: 45

Hide/show elements with react-select - elements not hiding

I am using the react-select library with a list of states, and then using that to hide/show my elements The elements are showing when I select them from the list, but then don't hide when they're removed. Here is the code:

import React from 'react';
import Select from 'react-select';

const options = [
    { value: 'ny', label: 'NY' },
    { value: 'ca', label: 'California' },
    { value: 'ak', label: 'Arkansas' }
];

export default class HomePage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    handleChange = (selectedOption) => {
        if (!selectedOption) {
            this.setState({})
        }
        else {
            const result = {}
            
            selectedOption.map((option) => {
                result[option.value] = true
            })

            this.setState(result)
        }
    }

    render() {
        return (
            <div>
                <Select
                    isMulti
                    onChange={this.handleChange}
                    options={options}
                />
                {this.state.ny && (
                    <div>NY State Images</div>
                )}
                {this.state.ca && (
                    <div>CA State Images</div>
                )}
                {this.state.ak && (
                    <div>AK State Images</div>
                )}
            </div>
        )
    }
}

Upvotes: 2

Views: 958

Answers (1)

Peter
Peter

Reputation: 1249

Something is strange with that React.Component.

Try to use functional component:

export default function HomePage() {
  const [state, setState] = useState({});

  const handleChange = selectedOption => {
    console.log("CHANGE_HAPPEN: ", selectedOption);
    if (!selectedOption) {
      setState({});
    } else {
      const result = {};

      selectedOption.forEach(option => {
        result[option.value] = true;
      });
      console.log("RESULT: ", result);
      setState(prev => result);
    }
  };

  return (
    <div>
      <Select isMulti onChange={handleChange} options={options} />
      {state.ny && <div>NY State Images</div>}
      {state.ca && <div>CA State Images</div>}
      {state.ak && <div>AK State Images</div>}
    </div>
  );
}

Upvotes: 1

Related Questions