I am new to React and trying to pass object through attributes but getting following error.
Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of MeetingComponent.
Here is my code:
Main.jsx
import React from 'react';
import MeetingComponent from '../components/Meeting.jsx';
let meeting = {
title: 'Some title'
};
class AppComponent extends React.Component {
render() {
return (
<div className="index">
<MeetingComponent dataMeeting={meeting} />
</div>
);
}
}
AppComponent.defaultProps = {};
export default AppComponent;
Meeting.jsx
import React from 'react';
class MeetingComponent extends React.Component {
render() {
return (
<div>{this.props.dataMeeting}</div>
);
}
}
MeetingComponent.defaultProps = {};
export default MeetingComponent;
How can I solve this? What is the best practice?
In order to pass a prop to a component all we have to do is name the prop and set it equal to some value. In the example above, we are passing a prop called name that is equal to a string. Passing a prop gives us access to the information in our Greeting component.
To pass an object as props to a component in React TypeScript: Define an interface for the type of the object. Pass an object of the specified type to the child component, e.g. <Employee {... obj} /> .
To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.
First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.
The problem is here
<div>{this.props.dataMeeting}</div>
You cannot render an object in React, maybe you were trying to do
<div>{this.props.dataMeeting.title}</div>
If you want to pass properties of an object , it can be done as follows:
<MeetingComponent {...meeting} />
To access title of the meeting object inside the Meeting component, you can do it by calling it directly this.props.title
You can render it as <div>{this.props.title}</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With