1

I am trying to iterate over the persons state and return multiple people through a component but I keep getting Uncaught Error: Objects are not valid as a React child (found: object with keys {allPeople}). If you meant to render a collection of children, use an array instead. It works if I put the map function directly in the return but not like this where I store it in a variable first and the enter the variable in the return, Thanks

 class App extends Component {
  
  state = ({
    persons: [
      {
        name: "John",
        age: 26,
        id: 1
      },
      {
        name: "Kim",
        age: 29,
        id: 2
      },
      {
        name: "Dave",
        age: 59,
        id: 3
      }
    ],
    newName: '',
    click: false
  })

  handlePeople = (e, id) => {

    this.setState({newName: e.target.value});
  }

  handleBtn = () => {
    this.setState({click: !this.state.click})
  }

  handleDelete = (e) => {
    console.log(e)
    
  }

    render() {
    let allPeople = null;
    allPeople = ( 
      <div>
          {this.state.persons.map((person, index) => {
            console.log(typeof person.name)
                 return <NameBox
                   key={person.id}
                   clickDel={() => this.handleDelete(index)}
                   name={person.name}
                   age={person.age}
                   changed={(e) => this.handlePeople(e, person.id)}
                   />
          })}
      </div>
    )
    console.log(allPeople)
    return (
      <div className="App">
        <h1>Person Manager</h1>
        <p>This is really working</p>
        <ClickBtn toggle={this.handleBtn} color={this.state.click}/>
        {this.state.click === false ? null : {allPeople}}
      </div>
    );
  }
  
}

export default App;

1 Answer 1

2

The problem is you're returning an object on this line:

{this.state.click === false ? null : {allPeople}}

In this case, {allPeople} is the same as {allPeople: allPeople}

It could be {this.state.click === false ? null : allPeople}

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I couldn't figure out why because all the other code seemed good! lol

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.