Preventing Close Of Select Input On Selection In React
How can I prevent a
Solution 1:
According to this answer, it’s not really possible with a native <select>
element—at least not quite like you’d expect. So I see a couple of possibilities:
Create a “fake” dropdown menu with an unordered list or any other non-form element, as in the answer that Jon Uleis pointed out in the comment above.
If you’d still prefer to use the native
<select>
element, there’s a slightly hacky approach which involves setting thesize
attribute of the element onchange
(and optionally, removing it onblur
).Here’s a quick example of what that might look like in React:
classHelloextendsReact.Component {
constructor(props) {
super(props);
this.state = { isFocused: false };
this.handleChange = this.handleChange.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
handleChange(e) {
this.setState({ isFocused: true });
}
handleBlur(e) {
this.setState({ isFocused: false });
}
render() {
return (
<selectonChange={this.handleChange}onBlur={this.handleBlur}size={this.state.isFocused
? this.props.options.length:false}>
{this.props.options.map((option, index) => (
<optionkey={option}>{option}</option>
))}
</select>
);
}
}
const options = [
'This should “stay open”',
'on change.',
'It should also “collapse”',
'on blur.'
];
ReactDOM.render(
<Hellooptions={options} />,
document.getElementById('root')
);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="root"></div>
Post a Comment for "Preventing Close Of Select Input On Selection In React"