So i’m making this React exercise where i use setState but it’s returning the following error.
Objects are not valid as a React child (found: object with keys {_reactName, _targetInst, type, nativeEvent, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, isDefaultPrevented, isPropagationStopped})
Here’s the code.
`
import React, { Component } from "react";
export default class Mega extends Component {
constructor(props) {
super(props)
this.state = {
qtdeNum: this.props.qtdeNum
}
this.alterarQtdeNum = this.alterarQtdeNum.bind(this)
}
alterarQtdeNum = (qtde) => {
this.setState({qtdeNum: qtde})
}
render() {
return (
<><p className="pnum">Gerador de Mega-Sena - {this.state.qtdeNum} </p><input type='text' placeholder="Qtde de Numeros" value={this.state.qtdeNum}
onChange={this.alterarQtdeNum}></input></>
)
}
}`
I noticed this has to do with the this.setState({qtdeNum: qtde}) line as everytime i alter qtde, exemple: this.setState({qtdeNum: this.qtde}) the error stops showing but the qtdeNum doesn’t change the state.
2
Answers
The problem is the
onChange
event handler, which receives an event object, not the value of the input field. You’re trying to set state directly with the event object.Try changing this:
to this:
You can you this code.
I just add one static value instead of your props.
If you notice in alterarQtdeNum method if you console log your qtde you got full element over there you have to get value by qtde.target.value.