Last active
January 11, 2021 14:08
-
-
Save trafficinc/2692806fd4ef054f74dc5dd3cd945aca to your computer and use it in GitHub Desktop.
React: Pass data from Child to Parent Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import { render } from "react-dom"; | |
const styles = { | |
fontFamily: "sans-serif", | |
textAlign: "center" | |
}; | |
class ChildComponent extends Component { | |
state = { | |
selectedCode: "", | |
selectedLanguage: [] | |
}; | |
handleLangChange = () => { | |
let lang = "French"; | |
this.props.onSelectLanguage(lang); | |
}; | |
render() { | |
return ( | |
<div> | |
<button onClick={this.handleLangChange}>click</button> | |
</div> | |
); | |
} | |
} | |
// App = parent | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
language: "" | |
}; | |
} | |
handleLanguage = (langValue) => { | |
this.setState({ language: langValue }); | |
}; | |
render() { | |
return ( | |
<div style={styles}> | |
<div> | |
<ChildComponent onSelectLanguage={this.handleLanguage} /> | |
</div> | |
<h2>{this.state.language}</h2> | |
</div> | |
); | |
} | |
} | |
/* | |
Will output: [Click] French | |
*/ | |
render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment