Getting the value of selected item in Dropdown react-bootstrap - javascript

I want to get the value of selected item in Dropdown. I uses react-bootstrap. I tried placing onSelect={(e) => console.log(e)} at <Dropdown>, <Dropdown.Menu> and <Dropdown.Item> but on selecting one country all of above gives me null.
Dropdown and items are rendered correctly.
please help.
return (
<div>
<FormGroup className={styles.formControl}>
<Dropdown >
<Dropdown.Toggle variant="success" id="dropdown-basic">
Select a Country
</Dropdown.Toggle>
<Dropdown.Menu onSelect={(e) => console.log(e) } className={styles.dropdown_menu}>
{countries.map((country,i) => <Dropdown.Item key={i}>{country}</Dropdown.Item> )}
</Dropdown.Menu>
</Dropdown>
</FormGroup>
</div>
)

const [selectedItem, setSelectedItem] = useState(null);
return (
<div>
<FormGroup className={styles.formControl}>
<Dropdown >
<Dropdown.Toggle variant="success" id="dropdown-basic">
{selectedItem?selectedItem:"Select a country"}
</Dropdown.Toggle>
<Dropdown.Menu className={styles.dropdown_menu}>
{countries.map((country, i) => <Dropdown.Item onSelect={()=>setSelectedItem(country)} key={i}>{country}</Dropdown.Item> )}
</Dropdown.Menu>
</Dropdown>
</FormGroup>
</div>
)
I hope onSelect is the correct handler for the component. Just cross verify that. This should work I suppose.
useState(null) can also be useState(props.value) in case you're passing down something from parent. That's up to you.

Related

Dropdown is malfunctioning in react-bootstrap

I am using Dropdown component from react-bootstrap but when I am clicking on it the items show in a horizontal line not vertical and when I am clicking on it again it is untoggled.
Here is my code:
const CustomMenu = React.forwardRef(
({ children, style, className, 'aria-labelledby': labeledBy }, ref) => {
const [value, setValue] = useState('');
return (
<div
ref={ref}
style={style}
className={className}
aria-labelledby={labeledBy}
>
<Form.Control
autoFocus
className="mx-3 my-2 w-auto"
placeholder="Type to filter..."
onChange={(e) => setValue(e.target.value)}
value={value}
/>
<ul className="list-unstyled">
{React.Children.toArray(children).filter(
(child) =>
!value || child.props.children.toLowerCase().startsWith(value),
)}
</ul>
</div>
);
},
);
render(
<Dropdown>
<Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components">
Custom toggle
</Dropdown.Toggle>
<Dropdown.Menu as={CustomMenu}>
<Dropdown.Item eventKey="1">Red</Dropdown.Item>
<Dropdown.Item eventKey="2">Blue</Dropdown.Item>
<Dropdown.Item eventKey="3" active>
Orange
</Dropdown.Item>
<Dropdown.Item eventKey="1">Red-Orange</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>,
);

React - I'm using the onclick option which requires a variable from a component that dynamically renders a series of elements, but it doesn't work

dropdownClick =(value ) => {
this.setState({searchGroup: value.name, elementSelected: value})
}
( I tried inserting the setState block inside the onClick and it do not worck too )
<InputGroup className="mb-2">
<Input value={this.state.searchGroup} onChange={(e) => this.filtergroups(e.target.value)} />
<InputGroupButtonDropdown addonType="append" isOpen={this.state.drop} toggle={this.AbrirCerrarDropdown} >
<DropdownToggle caret className="red button">Grupos</DropdownToggle>
<DropdownMenu>{this.state.skillGroupsFiltered.map((element, index) => (
<DropdownItem key={index} onClick={() => this.dropdownClick(element)}>{element.name}</DropdownItem>
))}
</DropdownMenu>
</InputGroup>

How to attach a function to Dropdown.Toggle on React Bootstrap?

I'm trying to execute a function when my React Bootstrap Dropdown.Toggle is clicked.
I tried adding onClick like the following but that breaks the dropdown functionality altogether and doesn't show the dropdown menu on click:
<Dropdown>
<Dropdown.Toggle variant="success" id="dropdown-basic" onClick={myFunction}>
Dropdown Button
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">Action</Dropdown.Item>
<Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
<Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
Is there any way of preserving the original functionality of the toggle and still executing an additional function when it is clicked?
Looks like you're overriding the inbuilt onClick, maybe you can attach the event listener on the Dropdown itself and check whether it was triggered from the button.
<Dropdown
onClick={e => {
if (e.target.id === "dropdown-basic") {
//do something
}
}}
>
<Dropdown.Toggle variant="success" id="dropdown-basic">
Dropdown Button
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">Action</Dropdown.Item>
<Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
<Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
const onSelect = (eventKey, event) => {
event.preventDefault();
event.persist();
event.stopPropagation();
console.log(eventKey) // selected event will trigger
}
<Dropdown className="d-inline mx-2" onSelect={onSelect}>
<Dropdown.Toggle id="dropdown-autoclose-true">
Default Dropdown
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item eventKey="1" href="#">Menu Item</Dropdown.Item>
<Dropdown.Item eventKey="2" href="#">Menu Item</Dropdown.Item>
<Dropdown.ItemeventKey="3" href="#">Menu Item</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>

Transform a dropdown from Material UI to Bootstrap

I need to do this transformation because the dropdown from Material UI looks bad.
Beside of that, the code is working fine. It is a dropdown with multiple choices, it loads a list of strings and their corresponding images and when they are filtered by that category/categories are shown in the table.
This is the working code with Material UI:
import {
Select,
MenuItem,
FormControl,
InputLabel,
} from '#material-ui/core';
const platforms = ['a', 'b', 'c', 'd'];
<FormControl className='searchPlatform'>
<InputLabel id='platforLabel'>Platform</InputLabel>
<Select
labelId='platforLabel'
id='platforLabel'
value={this.props.platformFilter}
renderValue={this.getSelectedPlatformFilter}
onChange={this.handleChangePlatform}
multiple
>
{platforms.map((platform) => (
<MenuItem key={platform} value={platform}>
<div>
<img
src={this.showicon(platform)}
alt=''
height={17}
width={17}
/>
{platform}
</div>
</MenuItem>
))}
</Select>
</FormControl>
And the next one is what I've tried with Bootstrap. I don't know how to trigger the dropdown on onChange. I've tried to put onClick on Dropdown.Item in order to call the same trigger as in onChange from Dropdown.Menu
import { Dropdown } from 'react-bootstrap';
<Dropdown>
<Dropdown.Toggle variant='success' id='dropdown-basic'>
Dropdown Button
</Dropdown.Toggle>
<Dropdown.Menu
value={this.props.platformFilter}
renderValue={this.getSelectedPlatformFilter}
onChange={this.handleChangePlatform}
>
{platforms.map((platform) => (
<Dropdown.Item
eventKey={platform}
value={platform}
onClick={this.handleChangePlatform}
>
<div>
<img
src={this.showicon(platform)}
alt=''
height={17}
width={17}
/>
{platform}
</div>
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
Try onSelect prop on <Dropdown> component, as it's a callback fired when a menu item is selected.
(eventKey: any, event: Object) => any
It would be something like:
<Dropdown onSelect={handleChangePlatform}>
<Dropdown.Toggle variant='success' id='dropdown-basic'>
Dropdown Button
</Dropdown.Toggle>
<Dropdown.Menu>
// ... rest of code
</Dropdown.Menu>
</Dropdown>

Adding a icon to React Bootstrap Dropdown

I'm trying to add an icon to my react dropdown button as shown in the following button.
I couldn't find a way to implement this with the react bootstrap package i'm using.
https://react-bootstrap.github.io/
I tried using the normal bootstrap 4 to to this. But found out that it needs jquery to open the dropdown menu. How can i add a icon to my react bootstrap drop down?
My code
<DropdownButton id="example-month-input-2" title={this.state.weekselectedType}>
<Dropdown.Item onClick={() => this.changeWeekValue('a')}>A</Dropdown.Item>
<Dropdown.Item onClick={() => this.changeWeekValue('b')}>B</Dropdown.Item>
<Dropdown.Item onClick={() => this.changeWeekValue('c')}>C</Dropdown.Item>
</DropdownButton>
I managed to remove the default dropdown icon using the following css
.dropdown-toggle::after {
display:none !important;
}
React Bootstrap allows you to customise Dropdown by passing in custom subcomponents. To customise the toggle button, you can use:
// The forwardRef is important!!
// Dropdown needs access to the DOM node in order to position the Menu
const CustomToggle = React.forwardRef(({ children, onClick }, ref) => (
<a
href=""
ref={ref}
onClick={e => {
e.preventDefault();
onClick(e);
}}
>
{/* Render custom icon here */}
▼
{children}
</a>
));
render(
<Dropdown>
<Dropdown.Toggle as={CustomToggle} id="dropdown-custom-components">
Custom toggle
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item eventKey="1">Red</Dropdown.Item>
<Dropdown.Item eventKey="2">Blue</Dropdown.Item>
<Dropdown.Item eventKey="3" active>
Orange
</Dropdown.Item>
<Dropdown.Item eventKey="1">Red-Orange</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>,
);
Docs
You can easily add an icon to the dropdown button of react-bootstrap.
<NavDropdown title="Dropdown" id="collasible-nav-dropdown">
Change this code to the code given below:
<NavDropdown
title={
<span>
<i className='fad fa-newspaper'></i> Dropdown
</span>
}
id='collasible-nav-dropdown'>
Now your code will look like that.
<NavDropdown
title={
<span>
<i className='fad fa-newspaper'></i> Dropdown
</span>
}
id='collasible-nav-dropdown'>
<NavDropdown.Item href='#action/3.1'>Action 1</NavDropdown.Item>
<NavDropdown.Item href='#action/3.3'>Action 2</NavDropdown.Item>
</NavDropdown>
Note: The code I have shared is taken from react-bootstrap version 2.0.0.
https://react-bootstrap.github.io/components/navbar/
here's with the Icon
<DropdownButton id="example-month-input-2" title=
{this.state.weekselectedType}>
<Dropdown.Item onClick={() => this.changeWeekValue('a')}><i
class="fa fa-chevron-down"></i></Dropdown.Item>
<Dropdown.Item onClick={() =>
this.changeWeekValue('b')}>B</Dropdown.Item>
<Dropdown.Item onClick={() =>
this.changeWeekValue('c')}>C</Dropdown.Item>
</DropdownButton>
font-awesome

Categories