jon
jon

Reputation: 1581

react redux get the a property of container

I have multiple 'sections' in the store. Each section has an object_id.

This is my sections reducer:

export default function () {
  return [
    {
      object_id: 1,
      title: "section_1"
    },
    {
      object_id: 2,
      title: "section_2"
    },
    {
      object_id: 3,
      title: "section_3"
    }
  ]
}

I loop through the store sections and add them to the DOM, however when they get added the ownProps of mapStateToProps appears to be an empty object.

import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

class Section extends Component {

  render() {
    console.log(this.props.object_id);
  }

}

function mapStateToProps(state,ownProps) {
  return { 
    object_id: ownProps.object_id,
    sliders: state.sliders
  };
}

export default connect(mapStateToProps)(Section);

Ideally, I want to be able to loop through the sliders that are in the store and see if they have a section_id that matches the sections object_id, however I'm stuck at step 1!

Upvotes: 0

Views: 49

Answers (2)

jon
jon

Reputation: 1581

So it appears the problem was - in the container that was adding the sections, I also need to pass the data. So:

  listSections(){
    return this.props.sections.map((section) => {
      return (
        <Section />
      );
    });
  }

becomes:

  listSections(){
    return this.props.sections.map((section) => {
      return (
        <Section my_section_properties={section} />
      );
    });
  }

I now have access to the my_section_properties data object within my section container.

To the people that know, does this seem like a best practice way of doing this?

Upvotes: 0

Samo
Samo

Reputation: 8240

In your mapStateToProps selector, ownProps should have an object_id property. Assuming state.sliders is an array, you can use .some to inspect the array for a slider that has a matching id. .some will return true if it's found, false otherwise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

return {
  hasMatchingSlider: state.sliders.some(s => s.section_id === ownProps.object_id)
}

Upvotes: 2

Related Questions