1

I have a parent component which is a set of child filter menu components. Each child component has a group of radio buttons, and the buttons all determine whether they are checked via their state.

In the parent component, when there is at least one filter for which the user has made a selection, a list of buttons appears of the selected filter options.

When one of these buttons is clicked, it should call a function within that child component to reset its radio groups.

I have seen here and here how to call a function within a single child ref when that ref is known, but how would I accomplish this when the refs are generated in a loop, and I want to only to call the ref of the specific child component that matches the button that was clicked?

Here is the relevant [pseudo-code]:

//FILTERS.JS
{filters.map((filter, index) => {
    return (
        <FilterContainer
            key={`filter--${filter.id}`}
            //NEED UNIQUE REF HERE THAT I CAN CALL
        />
    )
})}

handleClearSelectedFilter = ()=>{
    this.[matchingFilterContainerRef].current.resetRadioGroup();
}

where matchingFilterContainerRef would be the dynamic ref I match to the button that was clicked for the corresponding filterContainer child component.

mheavers
  • 29,530
  • 58
  • 194
  • 315

2 Answers2

1

With hopes I understand your issue correctly, I would like to suggest a different approach.

In the parent component you have a state which hold the filters. each of these filters has its own set of values. The parent then maps over the filters and passes each FilterContainer the props it needs, like the values for it, and also a callback function to when there was a change.

According to the values, the FilterContainer knows how to render its radio buttons. Data is flowing from the parent to the child in a single direction.

Once a radio button is clicked, you will call the callback given by the parent with the filter field and current value, e.g. a gender radio button was clicked, you will call this.props.onValueChange('gender', 'female').

The parent will then receive the callback and set its filters state accordingly. The state changes, the filters get rendered again with the new data.

Hope this helps :)

  • I think I see what you're saying - I should move to managing the active radio button via props coming from the parent - this is probably a better approach. I'm going to select the answer from Rahul because it technically answers this particular question more accurately, but I agree this would be a better way to structure. – mheavers May 02 '19 at 18:48
0

You can do like this

{filters.map((filter, index) => {
return (
    <FilterContainer
        key={`filter--${filter.id}`}
        ref={`ref_${filter.id}`}
        //NEED UNIQUE REF HERE THAT I CAN CALL
    />
)})}

And when you want to access it:

this.refs[`ref_${filterId}`]

See more here reactjs-dom-dynamic-refs

Rahul Saini
  • 216
  • 1
  • 16