Reputation: 3407
I'm trying to get my head around how I can affect a parent component through a child component. I know that react is designed not to really do this but how would you achieve it in the scenario below?
You have a page where you have your data, that data is passed into a component to be displayed. You then have a component that is based around sorting and filtering. You need to be able to use changes to the sort filter applicable to the page component so that the data can be manipulated.
Thanks
e.g.
> Page Component (this is where i get my data)
>> Filtering & Sort Component (this is where I want to change the data)
>> Data Listing Component (data passed into this)
Upvotes: 2
Views: 107
Reputation: 3861
Pass down callbacks which will be called when a user is interacting with your filtering and sort components
import React, { PropTypes } from 'react'
class Page extends React.Component {
updateFiltering(params) {
this.setState({data: /* */})
}
updateSort(params) {
this.setState({ data: /* */})
}
render () {
return (
<div>
<Filtering
onFilter={this.updateFiltering} onSort={this.updateSort}>
</Filtering>
<DataListing data={this.state.data}></DataListing>
</div>);
}
}
the onFilter
and onSort
props would be then used within your components for onChange
props on input elements.
class Filtering extends React.Component {
onChange(event) {
// do something with your filter or just give it directly to the callback
this.props.onFilter(event.target.selected)
}
render () {
return (
<select onChange={this.onChange}></select>
);
}
}
Upvotes: 2
Reputation: 4945
You can pass methods as props also. Then child a passes a change to parent and parent updates child b.
Upvotes: 1