React: Child Component Filtering Parent Component Props

I’m confused why this isn’t working. I can do an API fetch, and filter the data just fine. But, the parent component already has fetched this data, so I need to use it without doing another call.

Parent Component:(I want to filter the data set in contacts in a child of this component)

class Database extends Component {
        constructor(props){
            super(props);

            this.state = {
                clients: [],
                contacts: []
            }
        }

I pass the contacts array of objects to the child component like so:

<Container className="database">
   {this.state.clients.map(client => (
     <ClientCard
        key={client.id}
        short={client.short}
        client={client.client}
        {...this.state}
      />
    ))}
 </Container>

Then in my child component, I am filtering the contacts data for use in my child component, so I have a beginning state of:

class ClientCard extends Component {
    constructor(props){
        super(props);

        this.state = {
            showHide: false,
            filteredContacts: []
        }

So what I would like to do now, is upon componentDidMount, filter the props data like so:

this.setState({
    filteredContacts: this.props.contacts.filter(contact => this.props.contacts.short === this.props.short)
     });

I’m not getting any errors, but it’s also not setting the state of filteredContacts as needed either. The short mentioned in the code is an abbreviation for the clients stored in the array as an object property I’m using to help me filter.

1 thought on “React: Child Component Filtering Parent Component Props”

  1. You need to use the contact passed down to the filter function in order to filter the contacts in that array. Presumably each contact holds a short property to which you want to compare it against the prop short of the component.

    this.setState({
        filteredContacts: this.props.contacts.filter(contact => contact.short === this.props.short)
    });
    

    There shouldn’t be a this.props.contacts.short since this.props.contacts is an array.

    Reply

Leave a Comment