skip to Main Content

I’m using the react-select library in a React project to render a dropdown select box. I have defined an options array that contains a single option with the label "a". I have also defined an onChange function that should log the selected option to the console when an option is selected.

Additionally, I’m using the react-bootstrap library’s Modal component to create a popup, and the react-draggable library’s Draggable component to make the popup draggable.

Here’s my code:


import React from "react";
import Select from "react-select";
import Modal from 'react-bootstrap/lib/Modal'
import Draggable from 'react-draggable'

function App() {
  const onChange = (selectedOption) => {
    console.log("Selected Option:", selectedOption);
  };

  const options = [
    {
      label: "a",
    },
  ];

  const style={
    width:"100px",
    height:"100px",
    backgroundColor:"green"
  };  

  return (
    <div>
      <Draggable>
        <Modal show={true}>
          <Modal.Body>
            <div style={style}>Comp</div>
          </Modal.Body>
        </Modal>
      </Draggable>
      <div style={style}>
        Comp2
      </div>
      <Select options={options} onChange={(option) => onChange(option)} />
    </div>
  );
}

export default App;

Despite everything appearing to be set up correctly, when I open the dropdown and select the "a" option, the onChange function is not being called.

Can anyone help me figure out why the onChange function is not being called when an option is selected?

2

Answers


  1. In the options object, each element must contain a value property.

    const options = [
        {
            value: "a",
            label: "a",
        },
    ];
    
    Login or Signup to reply.
  2. Everything is working fine, but you need to set your modal show={false} initially.

    import React from 'react';
    import Select from 'react-select';
    import { Modal } from 'react-bootstrap';
    import Draggable from 'react-draggable';
    
    export default function App(props) {
      const onChange = selectedOption => {
        console.log('Selected Option:', selectedOption);
      };
    
      const options = [
        {
          label: 'a',
        },
      ];
    
      const style = {
        width: '100px',
        height: '100px',
        backgroundColor: 'green',
      };
      return (
        <div>
          <Draggable>
            <Modal show={false}>
              <Modal.Body>
                <div style={style}>Comp</div>
              </Modal.Body>
            </Modal>
          </Draggable>
          <div style={style}>
            Comp2
          </div>
    
          <Select options={options} onChange={option => onChange(option)} />
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search