I'm trying to use the Select form element from Bulma and can't figure out the most basic of questions... how to detect when an option is selected by the user? I want to call a function to change the website's language when a language select option is selected but can't figure out how to register a "select" event.
The element works just fine and toggles between two languages however what do I need to do to detect when one of the options is actually selected?
<div className="navbar-item">
<div className="select">
<select>
<option>English</option>
<option>Chinese</option>
</select>
</div>
</div>
I've tried using onChange
and onClick
events but neither of them work, for example:
<div className="navbar-item">
<div className="select">
<select>
<option onChange={() => changeLanguage('en')}>English</option>
<option onChange={() => changeLanguage('cn')}>Chinese</option>
</select>
</div>
</div>
Do I need to create separate React state vars for this and manage the selection myself?
ANSWER
Was able to piece together bits from the various answers get this working, I tried updating the answer so it's correct but also posting here for the benefit of the community.
Here's the JSX with Select options:
<div className="navbar-item">
<div className="select">
<select onChange={(e) => changeLanguage(e)}>
<option value="en" id="en">English</option>
<option value="cn" id="cn">中文</option>
</select>
</div>
</div>
And the corresponding change language function:
const changeLanguage = event => {
i18n.changeLanguage(event.target.value);
};
You should put onChange
handler on select
element instead of option
, here's react code to handle option change and alter your state
import React, { Component } from "react";
export default class App extends Component {
state = {
lang: "eng" // set english by default
};
onSelect = ev => {
this.setState({ lang: ev.target.value });
};
render() {
return (
<div className="navbar-item">
<div className="select">
<select onChange={this.onSelect}>
<option value="eng">English</option>
<option value="ch">Chinese</option>
</select>
</div>
</div>
);
}
}