Reputation: 481
I am using antd library as part of react application. For select option values are fetched from api and rendered in this format.
<Select
{...propsForSelect}
>
{this.props.data.map(e =>
<Option
key={e.key || e}
value={e.value || e}
title={e.title}
>
{`${e.key} | ${e.value}`}
/Option>
)}
</Select>
Once user selects an option I want to display only the value and not {${e.key} | ${e.value}
} value.
{${e.key} | ${e.value}
} is displaying in dropdown and when user selects an option need to show e.value alone.
CodeSandbox: https://codesandbox.io/s/tender-feynman-uhtn7
Upvotes: 1
Views: 9363
Reputation: 5953
class App extends React.Component {
state = {
genres: [
{ key: 1000, value: "1", display: "Action" },
{ key: 1001, value: "2", display: "Adventure" },
{ key: 1002, value: "3", display: "Comedy" }
],
selected: '' // A default value can be used here e.g., first element in genres
};
handleChange = key => {
this.setState({ selected: this.state.genres.find((object) => object.key === Number(key)).value });
};
render() {
return (
<div className="container">
<Select value={this.state.selected} onChange={this.handleChange} style={{ width: "50%" }}>
{this.state.genres.map(e => (
<Option key={e.key}>
{`${e.display} | ${e.value}`}
</Option>
))}
</Select>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
Upvotes: 2
Reputation: 8528
This is what the optionLabelProp
is for.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Select } from 'antd';
const { Option } = Select;
class App extends React.Component {
state = {
genres: [{"key": 1000, "value": "1", "display": "Action"},
{"key": 1001, "value": "2", "display": "Adventure"},
{"key": 1002, "value": "3", "display": "Comedy"}]
};
render() {
return (
<div className="container">
<Select
style={{width:"50%"}}
optionLabelProp="value"
>
{this.state.genres.map(e =>
<Option
key={e.key}
value={e.value}
>
{`${e.display} | ${e.value}`}
</Option>
)}
</Select>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container'),
);
Upvotes: 2
Reputation: 1238
Is this what you are looking for?
https://codesandbox.io/s/headless-river-1n0e3
Basically I just added a selected
property to each genre object, and then in the Select component's onSelect()
prop, passed a callback function that updates state and toggles the respective genre's selected
property to true.
Then, in the UI, I simply check if the selected
property is true for each genre and then conditionally render only the display
value in that case.
Upvotes: 2