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..