Hi I am currently working on reactjs but in very basic level. I was trying to parse data from parent to child as well as child to parent. Parent to child is working properly but child to parent I couldn't.
Here is the whole scenario... I have 3 components.. App, Home and User. From App component to Home component I want to parse data.. It is working properly. In Home component I have an Input field. If I write something and click on button then the input value will parse into App component. App is my parent and Home is child..
Here is the code... APP Component
constructor() {
super()
this.state = {
userName : ' '
};
}
changeUName(newName) {
this.setState({
userName: newName
});
console.log('user',newName); // Getting Undefined
}
render() {
return (
<div className="App">
<Home changeUser = {() => this.changeUName()} />
</div>
);
}
Child Component User
constructor(props) {
super();
this.state = {
userName: ''
};
}
changeUName(event) {
this.setState({
userName: event.target.value
});
}
nameChange() {
console.log(this.state.userName) // If I write "Test" in input field. I will get the value here.
this.props.changeUser(this.state.userName); // Once I parse this value, I am getting undefined..
}
render() {
return(
<div>
<h1> HOME Page</h1>
Name : <input type="text" value={this.state.userName} onChange={(event) => this.changeUName(event)} ref="uName"/><br/>
<button onClick={() => this.nameChange()}>Click</button>
</div>
)
}
I do not know where it is going wrong. Please guide me. Thanks in advance..
The culprit is this line of code:
You call
changeUName
without any parameter. You should write instead:Or
By the way, have you considered storing your user name into a redux store ? If you haven't studied that yet, you should definitely look into it. In this case you would store the user name in the redux store, and pass it to the App (and other components) by injecting it to their props.
The thing is that you are not binding the props recieved to the function definition. See the below snippet
Or else Specify the funtion with arrow function
and call it like