I want to change the state on click of a button in React. Essentially I am trying to update the value of the name displayed in my div by setting this.state.name equal to whatever is typed in the text-box.
What am I doing wrong here?
I also don't quite understand the difference between onClick={() => this.updateText()} and onClick={this.updateText()} and/or onClick={this.updateText}. Maybe it's related to that?
Form.tsx
import React from 'react';
export default class Form extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
title: "Enter a new name here",
description: "Hola",
textInput: null,
name: this.props.name
};
}
updateText() {
this.setState({
name: this.state.textInput
});
}
render() {
return (
<div className="App">
<div>{this.props.text} {this.state.name}</div>
<div>{this.state.age}</div>
<input type="text" placeholder={this.state.title}>{this.state.textInput}</input>
<br />
<button type="submit" onClick={() => this.updateText()}>Submit</button>
</div>
);
}
}
App.tsx
import React from 'react';
import './App.css';
import Form from "./Form";
class App extends React.Component {
render() {
return (
<div className="App">
<Form text="Hello" age={22} name="Thomas"/>
</div>
);
}
}
export default App;
this.state.name comes up as empty or null upon typing something and clicking the submit button.