0

Ok, I have a generic filters component which receives an index-filters component (set with properties in the index page) as a property. It will render it.

In the generic filters component, I have a method handleSingleFilter, which I need to pass to the index-filters component, but of course as the index-filters properties were set in the index page, it is not allowing me to update them.

In the index:

   <IndexFilters
      onSingleFilterChange={() => {
         return
      }}
   />

In the filters:

const { filters } = this.props
public handleSingleFilterChange = (filteredInfo: FilteredInfo) => {
    this.state = {
        filteredInfo
    }
}
public render() {
    filters.props.onSingleFilterChange = this.handleSingleFilterChange
    return (
        <div className={'filter-dropdown'}>
           {filters}
        </div>
    )
}

I get the following error: filters.tsx:36 Uncaught TypeError: Cannot assign to read only property 'onSingleFilterChange' of object '#'

Is there a way to make the property writable?

Gioia Fueter
  • 605
  • 1
  • 5
  • 16
  • 1
    Does this answer your question? [How to pass props to {this.props.children}](https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children) – Tripurari Shankar Jan 07 '20 at 13:34

3 Answers3

0

To answer your question which is

How to update a property of a component which has been passed itself as a property

check How to pass props to {this.props.children}

You can use React.cloneElement() here see https://reactjs.org/docs/react-api.html#cloneelement

something like this

const newFilters = React.cloneElement(
  this.props.filters,
  {onSingleFilterChange: this.handleSingleFilterChange},
);
return (
  <div className={'filter-dropdown'}>
    {newFilters}
  </div>
)

Tripurari Shankar
  • 3,308
  • 1
  • 15
  • 24
0

Ok, I ended up changing my logic so I could move the handleSingleFilterChange to the index, then no need to do anything hacky.

Gioia Fueter
  • 605
  • 1
  • 5
  • 16
-1

if filters is not rendered yet then you can do like this

<div className={'filter-dropdown'}>
  <filters onSingleFilterChange = {this.handleSingleFilterChange}>
</div>

otherwise no need to rewrite props, you can write value directly to any attribute of an object

filters.onSingleFilterChange = this.handleSingleFilterChange
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20