skip to Main Content

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


  1. 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:

        alterarQtdeNum = (qtde) => {
            this.setState({qtdeNum: qtde})
        }
    
    

    to this:

        alterarQtdeNum = (event) => {
            this.setState({qtdeNum: event.target.value})
        }
    
    Login or Signup to reply.
  2. You can you this code.
    I just add one static value instead of your props.

    class App extends Component {
     constructor() {
     super();
     this.state = {
      qtdeNum: "10",
     };
    
       this.alterarQtdeNum = this.alterarQtdeNum.bind(this);
     }
      alterarQtdeNum = (qtde) => {
        this.setState({ qtdeNum: qtde.target.value });
    };
    
    render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
        <h3>{this.state.age} years old</h3>
        <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>
      </div>
      );
     }
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search