Home >Web Front-end >JS Tutorial >Why Am I Getting 'Invariant Violation: Objects are not valid as a React child' in My React App?
React Error: Objects as Children
In React applications, "Invariant Violation: Objects are not valid as a React child" errors occur when attempting to render an object as a child of a component. This issue arises when the child is expecting a string, number, or element but receives an object instead.
In the given example, within the map function in the render method, this.onItemClick.bind(this, item) incorrectly passes the entire event object as a property to the onClick handler. Consequently, the onClick event handler receives the event with its properties as an object, triggering the error.
To resolve this, you can either use an arrow function inside the map to handle the click event and pass the necessary argument:
render() { const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => { return (<li onClick={(e) => this.onItemClick(e, item)} key={item}>{item}</li>); }); return ( <div> ... <ul> {items} </ul> ... </div> ); }
Alternatively, if you wish to preserve the event object, you can bind only the necessary parameter:
render() { const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => { return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>); }); return ( <div> ... <ul> {items} </ul> ... </div> ); }
The above is the detailed content of Why Am I Getting 'Invariant Violation: Objects are not valid as a React child' in My React App?. For more information, please follow other related articles on the PHP Chinese website!