简体   繁体   中英

Extract selected value from a dropdown in REACT

I am trying to write up a simple react application (using react bootstrap) which has a dropdown with some value.

The code for my react component is

import React, { Component } from 'react';

import { InputGroup, DropdownButton, Dropdown, FormControl, Row, Col } from 'react-bootstrap';

class Header extends Component {
handleSelect = selectedOption => {
    console.log(selectedOption.target);
}

state = {}
render() {
    return (
        <div>
            <h1>Top 3 Expert</h1>
            <hr />
            <Row>
                <Col></Col>
                <Col xs={3}>
                    <InputGroup className="mb-3">
                        <DropdownButton
                            onClick={this.handleSelect}
                            as={InputGroup.Prepend}
                            variant="outline-secondary"
                            title="Choose City"
                            id="input-group-dropdown-1" >
                            <Dropdown.Item href="#">Sydney</Dropdown.Item>
                            <Dropdown.Item href="#">Hobart</Dropdown.Item>
                        </DropdownButton>
                        <FormControl aria-describedby="basic-addon1" />
                    </InputGroup>
                </Col>
                <Col></Col>
            </Row>
        </div >
    );
}
}

export default Header;

In my handleSelect method, I am unable to fetch the values 'Sydney' and 'Hobart'. The output of

console.log(selectedOption.target);

is

<a href="#" class="dropdown-item" role="button">Sydney</a>

Please can you help with understanding how I can extract the selected value from the dropdown.

I have also tried to modify the handler to this

handleSelect = selectedOption => {
    console.log(selectedOption.target.value);
}

but It prints undefined.

Change your handler definition to this:-

handleSelect = selectedOption => {
    console.log(selectedOption.target.innerText);
}

There has to be better option than this though. react-bootstrap Dropdown should have some kind of handler where you don't need to play dirty accessing innerText like this.

Also your items should be wrapped inside <Dropdown.Menu></Dropdown.Menu> and your handler should be present on this instead of the DropdownButton .

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