Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Objects are not valid as a React child (found: object with keys {id, name})

Tags:

reactjs

I'm encountering an issue while compiling my reactJS component:

import React, { Component } from "react";

class StatefullComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        { id: 1, name: "Perceuse" },
        { id: 2, name: "disqueuse" },
        { id: 3, name: "marteau" },
        { id: 4, name: "clé de 17" },
        { id: 5, name: "meuleuse" }
      ],
      newItem: ""
    };
    this.addNewItemToState = this.addNewItemToState.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.removeThisItem = this.removeThisItem.bind(this);
  }

  sortItems() {
    this.setState({
      items: this.state.items.sort()
    });
  }

  addNewItemToState() {
    this.setState({
      items: [...this.state.items, this.state.newItem],
      newItem: ""
    });
  }

  removeThisItem(bidule) {
    const tmparray = this.state.items.filter(bazar => {
      return bazar.id !== bidule;
    });
    console.log(tmparray);
    this.setState({
      items: tmparray
    });
  }

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

  render() {
    return (
      <div className="statefull">
        <h2>Satefull component, build with a class</h2>
        <ul>
          {this.state.items.map(item => (
            <li className="lambda">
              {item}
              <button onClick={this.removeThisItem(item.id)}>
                supprimer cet item
              </button>
            </li>
          ))}
        </ul>
        <input
          type="text"
          placeholder="Ajouter un element"
          value={this.state.newItem}
          onChange={this.handleChange}
        />
        <button onClick={this.addNewItemToState}>Ajouter</button>
      </div>
    );
  }
}

export default StatefullComponent;

and my App.js:

import "./App.scss";
import React from "react";
import StatelessComponent from "./components/stateless-component";
import StatefullComponent from "./components/statefull-component";

function App() {
  return (
    <div className="App">
      <StatefullComponent />
    </div>
  );
}

export default App;

Why do I get this error?

'Error: Objects are not valid as a React child (found: object with keys {id, name}). If you meant to render a collection of children, use an array instead.'

Did I badly formatted my items array in my state? It's important to me to have an id because I want to be able to delete an item. Any clue? Thanks.

like image 497
Stéphane Joos Avatar asked Apr 03 '26 00:04

Stéphane Joos


2 Answers

That's because you are trying to render an object in map. Change your ul to this:

<ul>
 {
   this.state.items.map((item, index) => <li className="lambda" key={index}>{item.name}<button onClick={this.removeThisItem(item.id)}>supprimer cet item</button></li>)
 }
</ul>

Hope this works for you.

like image 200
Muhammad Zeeshan Avatar answered Apr 04 '26 12:04

Muhammad Zeeshan


You need to display name using {item.name} but not using {item}. This is reason you get that error.

Also I noticed the following issues:

1-) You need to add a key property to li tag like this: <li className="lambda" key={item.id}>. React needs key property in a list.

2-) You need to change onClick={this.removeThisItem(item.id)} to <button onClick={() => this.removeThisItem(item.id)}>. You are calling the removeThisItem method, but it shouldn't be called.

import React, { Component } from "react";
class StatefullComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        { id: 1, name: "Perceuse" },
        { id: 2, name: "disqueuse" },
        { id: 3, name: "marteau" },
        { id: 4, name: "clé de 17" },
        { id: 5, name: "meuleuse" }
      ],
      newItem: ""
    };
    this.addNewItemToState = this.addNewItemToState.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.removeThisItem = this.removeThisItem.bind(this);
  }

  sortItems() {
    this.setState({
      items: this.state.items.sort()
    });
  }

  addNewItemToState() {
    this.setState({
      items: [...this.state.items, this.state.newItem],
      newItem: ""
    });
  }

  removeThisItem(bidule) {
    const tmparray = this.state.items.filter(bazar => {
      return bazar.id !== bidule;
    });
    console.log(tmparray);
    this.setState({
      items: tmparray
    });
  }
  handleChange(e) {
    this.setState({
      newItem: e.target.value
    });
  }
  render() {
    return (
      <div className="statefull">
        <h2>Satefull component, build with a class</h2>
        <ul>
          {this.state.items.map(item => (
            <li className="lambda" key={item.id}>
              {item.name}
              <button onClick={() => this.removeThisItem(item.id)}>
                supprimer cet item
              </button>
            </li>
          ))}
        </ul>
        <input
          type="text"
          placeholder="Ajouter un element"
          value={this.state.newItem}
          onChange={this.handleChange}
        />
        <button onClick={this.addNewItemToState}>Ajouter</button>
      </div>
    );
  }
}

export default StatefullComponent;

Playground

like image 30
SuleymanSah Avatar answered Apr 04 '26 14:04

SuleymanSah