0

a React newbie having some issues passing down states and functions from Parent Component (App in this case) and accessing from Child Components (Main in this case). I'm sure it's one or two really simple mistakes, where am I getting tripped up?

Here is the project structure:

App
 |__ Rootstack
       |
       |__Favorites
       |__Main

And here is the stripped down code:

class Main extends React.Component {
  render() {
      return (
      <View>
         <Text>{this.props.favoritesList.length}</Text>
         <Card>
              onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
         </Card>
      </View>
        );
    }
}

class Favorites extends React.Component {
          ....
    }

const RootStack = StackNavigator(
  {
    Main: {
      screen: Main},
    Favorites: {
      screen: Favorites}
  },
  {
    initialRouteName: 'Main'
  }
);


export default class App extends Component<{}> {
  constructor(props) {
      super(props);
      this.state = {
        favoritesList: []
      };
    this.updateArr = this.updateArr.bind(this); //don't know if this is necessary?
    }

  updateArr=()=>{this.setState({ favoritesList: 
      [...this.state.favoritesList, 'new value']})};

  render() {
      return <RootStack {...this.state} updateArray={this.updateArr}/>;
    }
  }

Error I'm getting is enter image description here -- any ideas? Thanks in advance!

SpicyClubSauce
  • 4,076
  • 13
  • 37
  • 62
  • You are trying to send props through navigator and access it through your components. You can't send props through navigator this way. Look [this](https://github.com/facebook/react-native/issues/4323) instead it may help you. – B.Shrestha Feb 25 '18 at 05:35
  • first no need to bind an arrow function secondly you are passing props to a stateless component and also for navigator to receive props directly not possible. – Shahzad Feb 25 '18 at 05:37

1 Answers1

0

1-

This is not correct

       <Card  ... props should be here!!---  >
          onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
     </Card>

The correct answer is:

     <Card  
       onSwiped={() => {this.props.updateArray}} //the idea being that on a swipe, updateArray would add 1 to the 'favoriteList' in the parents state, and the favoritesList.length would update by +1.
      >
    </Card>

The meaning of the error is that the child of Card is expected to be an object and not .....

2-

this.updateArr = this.updateArr.bind(this); is not necessary since updateArr = () => ... is written in es6

Community
  • 1
  • 1
challenger
  • 2,184
  • 1
  • 18
  • 25