Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to pass data from child component to its parent in ReactJS?

I'm attempting to transfer data from a child component to its parent as follow:

const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguageCode: function(langValue) {
this.setState({language: langValue});
},

render() {
return (
<div className="col-sm-9" >
<SelectLanguage onSelectLanguage={this.handleLanguage}/>
</div>
);
});


and here is the child component:

export const SelectLanguage = React.createClass({
getInitialState: function(){
return{
selectedCode: '',
selectedLanguage: '',
};
},

handleLangChange: function (e) {
var lang = this.state.selectedLanguage;
var code = this.state.selectedCode;
this.props.onSelectLanguage({selectedLanguage: lang});
this.props.onSelectLanguage({selectedCode: code});
},

render() {
var json = require("json!../languages.json");
var jsonArray = json.languages;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={this.state.selectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});

Can anyone help me to find the problem?
by

2 Answers

rahul07
Parent:

<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>

Child:

handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
kshitijrana14
To pass data from child component to parent component
In Parent Component:
getData(val){
// do not forget to bind getData in constructor
console.log(val);
}
render(){
return(<Child sendData={this.getData}/>);
}

In Child Component:

demoMethod(){
this.props.sendData(value);
}

Login / Signup to Answer the Question.