I am getting an Error when I want to pass a function into my function Component in React
. where is the problem?
I have started learning React
and I am watching a tutorial. I have very simple function component with only one <p>
element, also I have a simple function in my App.js, everything works fine but when I am going to pass my function from App.js to my Function component I get an Error.
Well, I did the same as the tutorial. Although, everything is OK in the tutorial (as per Video) it does not work for me.
Could someone help me, and let me know what the problem is?
import React, { Component } from 'react';
import Person from './Person/Person';
import './App.css';
class App extends Component {
state = {
person: [
{ namd: "Ehsan", age: 36 },
{ name: "Mosen", age: 48 }
]
}
swichNameHandler = (newName) => {
this.setState({
person: [
{ name: newName, age: 37 },
{ name: "Mohsen", age: 49 }
]
})
}
render() {
return (
<div className="App">
<h1>this is react</h1>
<button onClick={this.swichNameHandler.bind(this, "ehsan")}>Click Here</button>
<Person
name={this.state.person[0].name}
age={this.state.person[0].age}
click={this.swichNameHandler} />
<Person
name={this.state.person[1].name}
age={this.state.person[1].age}
click={this.swichNameHandler}> he is my brother.</Person>
</div>
);
}
}
export default App;
import React from 'react';
//Create a new Component
const person = (props) => {
return (
<div>
<p onClick={props.click}> My name is {props.name} and I am {props.age} years old.</p>
<p>{props.children}</p>
</div>
)
}
export default person;
and this is the Error when I click on p element:
react-dom.development.js:57 Uncaught Error: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, _dispatchListeners, _dispatchInstances, nativeEvent, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, pageX, pageY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, movementX, movementY, isDefaultPrevented, isPropagationStopped})
If you meant to render a collection of children, use an array instead.
<Person name={this.state.person[0].name} age={this.state.person[0].age} click={() =>{this.swichNameHandler("New Name")}} />
– saurssaurav