I tried many ways to select some options from the select, but it didn't work. Could you help to solve my problem, please? When I do a console.log, the selected options change, but the frontend doesn't show it. It keeps the default option "Select the option." I am using react-bootstrap and firebase. I don't know what the error is. I was thinking about the browser, but it is not the problem.
class Formm extends Component {
constructor(props) {
super(props);
this.state = {
detail: "",
cost: 0,
category: ""
};
this.setCategory = this.setCategory.bind(this);
console.log(this.state);
}
setCategory = (e) => {
let index = e.target.selectedIndex;
this.setState({ category: e.target.value});
console.log(e.target.value)
};
render() {
const { detail, cost, category } = this.state;
return (
<div>
<FirebaseDatabaseProvider firebase={firebase} {...firebaseConfig}>
<FirebaseDatabaseNode path="category/">
{(data) => {
const { value } = data;
if (value === null || typeof value === "undefined") return null;
const values = Object.values(value);
return <div className="row justify-content-center">
<div className="form-group col-md-6">
<label htmlFor="">Insert the type:</label>
<select
onChange={this.setCategory}
value={category}
className="form-control"
>
<option value={null}>Select the option</option>
{values.map((value) => {
return (
<option key={value} value={value}>
{value}
</option>
);
})}
</select>
</div>
</div>;
}}
</FirebaseDatabaseNode>
</FirebaseDatabaseProvider>
</div>
It’s because you’re using “this” keyword inside of an arrow function that your set state doesn’t run.
“this” refers to the Class itself, but an arrow function, unlike a standard function, has no reference to the Class even though it’s defined within the Class.
Fortunately there’s an easy fix: If you change setCategory to a function using the function keyword your code will run as you expect.