Reputation: 615
I am using the following component to create a drop down. But if drop down has one value and d.datasetid is equal to 0 then that value should not come in drop down which means drop down should populate with blank also need to show a error message that value is not present. Please help me as I am very new to reactjs
import React from 'react'
import {Form, Col, FormGroup, ControlLabel, DropdownButton, MenuItem, ButtonGroup} from 'react-bootstrap'
const getId = (obj) => obj.datasetid + ''
export const DatasetSelector = ({label, dataArr, selected, onChange}) => {
const onChangeHandler = (key) => {
onChange(key)
}
let title = 'Select a Dataset'
if (selected && dataArr.length > 0) {
const ds = dataArr.filter((d) => getId(d) === selected)
if (ds[0]) {
title = ds[0].datasetname
}
}
return (
<Form horizontal>
<FormGroup controlId='dsSelector'>
<Col componentClass={ControlLabel} xs={12} sm={4} md={4}>{label}</Col>
<Col xs={12} sm={8} md={8}>
<ButtonGroup vertical={false}>
<DropdownButton id='DatasetSelect' bsSize='small' title={title} onSelect={onChangeHandler}>
{dataArr.map(d =>
<MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
<b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
</MenuItem>
)}
</DropdownButton>
</ButtonGroup>
</Col>
</FormGroup>
</Form>
)
}
Upvotes: 1
Views: 47
Reputation: 64657
You could do it like this:
{dataArr.length === 1 && dataArr[0].datasetid === 0 ? '' : dataArr.map(d =>
<MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
<b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
</MenuItem>
)}
Or you could do:
const MenuItems = ((empty) => {
if (empty) return '';
return dataArr.map(d =>
<MenuItem key={getId(d)} active={getId(d) === selected} eventKey={getId(d)}>
<b>{d.datasetname}</b> - <small>{d.datasetdescription}</small>
</MenuItem>
)}
})(dataArr.length === 1 && dataArr[0].datasetid === 0);
// ...
return (
// ...
<DropdownButton id='DatasetSelect' bsSize='small' title={title} onSelect={onChangeHandler}>
{MenuItems}
</DropdownButton>
// ...
)
Upvotes: 2