React: Passing data to parent component

omar assadi
Aug 24, 2017 · 2 min read

For a lot of you this task would look very obvious but I decided to write a small article since I think that beginners would very easily get stuck in this situations where you are asking yourself : which is the right way to pass datas from my child component to the parent (container) one that for example has the method to save data ?

Example:

Parent Component

class CartelContainer extends Component {
static propTypes = {
actions: PropTypes.object.isRequired
};
state = {
couponCode : ''
}
checkOut = () => {
const data = {
data1: '',
data2: '',
couponCode: this.state.couponCode
}
this.props.actions.checkOut(data);
}
updateCouponCode = (couponCode) => {
this.setState({
couponCode: couponCode
})
}
render () {
return (
<form onSubmit={this.checkOut}>
...Cartel inputs
<CouponCode onChange={this.updateCouponCode} />
<button type='submit'>Save</button>
</form>
)
}
}

Child Component

class CouponCode extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired
};
state = {
code : ''
}
handleOnChange = (e) => {
const value = e.target.value;
this.setState({
code: value
});
// manipulate, check data if needed this.props.onChange(value);
}
render () {
return (
<div className='coupon-container'>
<input
type='text'
name='coupon-code'
value={this.state.code}
onChange={this.handleOnChange} />
</div>
)
}
}

On every change of the child component we can update the state in the parent one so we have updated data of couponCode.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade