i am new to React and i try to create a URL-String for consuming a API. Here is a minimalistic code snippet:
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css"
class Unternehmenseinstellungen extends React.Component {
constructor(props) {
super(props);
this.state = {
uname: ""
};
this.handleUName = this.handleUName.bind(this);
}
handleUName(e) {
this.setState({uname: e.target.value});
}
Unternehmensenden() {
if (document.getElementById("uname").value === "") {
alert("Please fill all fields");
}
else {
var apiEndpoint = "http://localhost:8080/erstelleUnternehmen?uname=" + this.state.uname;
alert(apiEndpoint)
}
}
render() {
return (
<div>
<div>
<input placeholder="e.g. Bike company"
value={this.state.uname}
onChange={this.handleUName}
style={{...}}
type="text" id="uname" required/>
</div>
<button
style={{...}}
className="btn btn-pill btn-dark" onClick={this.Unternehmensenden}>Show my state
</button>
<div>
<h3>State-Test:</h3>
<p>Name: {this.state.uname}</p>
</div>
</div>
);
}
}
If i render this component, my "State-Test" is working and shows me my text that i write in the input box. But if i call my function "Unternehmensenden" the alert in the else condition always get an Error with the message "TypeError: Cannot read property 'state' of undefined".
What is the Reason for this? Did i have forgotten something?