Reputation: 1131
I'm currently building a very simple component with one input, where a User can type a number in.
However, the input has the following problems:
I can't figure out what's wrong... It's a really straightforward component, and I've basically just copied/pasted across from other inputs.
Note - there's a componentDidMount in there, but I've taken it out for easier reading.
Any pointers would be appreciated.
Here's my component:
class Add extends Component {
constructor(props) {
super(props)
this.state = {
balance: '',
add: '',
}
this.onChange = this.onChange.bind(this);
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value})
}
render() {
const calculateUpdatedBalance = () => {
return this.state.balance + this.state.add
}
return (
<section className="edit-balance-section">
<div className="edit-balance-container">
<DashboardReturn />
<div className="edit-balance-content">
<p className="edit-balance-paragraph">How much would you like to add to your balance?</p>
<div className="edit-balance-balance-container">
<p className="edit-balance-balance-paragraph">Current Balance: </p>
<span className="edit-balance-original">-£{this.state.balance}</span>
</div>
<div className="edit-balance-balance-container">
<p className="edit-balance-balance-paragraph">Updated balance: </p>
<span className="edit-balance-updated">-£{calculateUpdatedBalance()}</span>
</div>
<form>
<input className="edit-balance-input" type="number" name="balance" value={this.state.add} onChange={this.onChange} step="0.01" />
<button className="edit-balance-button" type="submit">Save</button>
</form>
</div>
</div>
</section>
)
}
}
export default Add
Upvotes: 0
Views: 231
Reputation: 4470
I found the issue, Actually you're setting input(name="balance")
to this.state.balance
and using this.state.add
for value which always ''
. You just need to change the name balance
to add
. Here's working in example with your code.
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value}) // e.target.name will be `balance or add`
}
<input className="edit-balance-input" type="number" name="add"<-- here value={this.state.add} onChange={this.onChange} step="0.01" />
or
<input className="edit-balance-input" type="number" name="balance" value={this.state.balance} onChange={this.onChange} step="0.01" />
Upvotes: 2