Skip to content

Higher-Order Components not reacting to change in props. #7345

@purezen

Description

@purezen

I am trying to implement basic filtering functionality using Higher-Order Components.

The HOC looks like,

filter.js

import React, { Component } from 'react'

export default function Filter(FilteredComponent) {
  return class FilterComponent extends Component {
    constructor(props)  {
      super(props)
    }

    generateList() {
      if (this.props.searchTerm !== undefined)  {
        let re = new RegExp(state.searchTerm,'gi')
        return this.props.currencyList.filter((c) => c.match(re))
      }
      else {
        return this.props.currencyList
      }
    }

    render() {
      return (
        <FilteredComponent
          filteredList={this.generateList()}
          {...this.props}
        />
      )
    }
  }
}

However, on typing in the input element, the generateList() method is not being called. I tried using componentWillReceiveProps but that does not get triggered as well. Though it is happily passing on the props, searchTerm and setSearchTerm to the search component.

The component using the props is,

SearchResults.js

import React from 'react'

const SearchResults = (props) => {
  // const listData = props.filteredList.map (item => <div>{item}</div>)

  return (
    <div>
      Here are the search results.
      <br />
      <input
        type="text"
        value={props.searchTerm}
        onChange={props.setSearchTerm}
      />
    </div>
  )
}

export default SearchResults

and the corresponding container is,

SearchResultsContainer.js

import {connect} from 'react-redux'
import SearchResults from '../components/SearchResults'
import * as a from '../actions'
import Filter from '../enhancers/filter'

const getSearchTerm = (state) => (state.searchTerm === undefined) ? '' : state.searchTerm

const mapStateToProps = (state) => {
  return  {
    searchTerm: getSearchTerm(state),
    currencyList: state.currencyList
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    setSearchTerm: (e) => {
      dispatch(a.setSearchTerm(e.target.value))
    }
  }
}

const SearchResultsContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(SearchResults)

export default Filter(SearchResultsContainer)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions