Ad

Modifying State/props In A Parent

- 1 answer

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)
Ad

Answer

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>
    );
  }
}
Ad
source: stackoverflow.com
Ad