Reputation: 39
how do i make a text input inside of a React component that will show a text box with a submit button , next to it there should be a number that will be incremented each time i click "submit". The increment value (that is added to the counter) will be the length of each word that was submitted.
so lets say i write in the text box "hi" (2 letters) and click submit - my counter should show 2 then if i write there "welcome" - not the counter will add 7 ==> so it will show 9
the local state should be inside of the class component.
Thanks :)
this is what i got :
import React, { Component } from 'react'
export class TextInput extends Component {
constructor(){
super()
this.state = {
count: 0
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
render(){
return(
<div>
<h1>{this.state.count}</h1>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button onClick = {this.handleClick}>Change</button>
</div>
)
}
}
export default TextInput
Upvotes: 0
Views: 58
Reputation: 53934
You need to use the value
state and add its length to the count
state:
import React, { Component } from "react";
export class TextInput extends Component {
state = {
count: 0,
value: "",
};
handleClick = () => {
this.setState((prevState) => {
return {
count: prevState.count + prevState.value.length,
value: "",
};
});
};
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
return (
<div>
<h1>{this.state.count}</h1>
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Change</button>
</div>
);
}
}
export default TextInput;
Upvotes: 1