chobo2
chobo2

Reputation: 85765

How to Pass in Functions in ReactJs?

I am using the redux pattern but I am not sure just pass in 1+ of my actions methods to a dumb component.

right now in my smart component I have something like

<AddStorageItemButton {...this.props} />

but this of courses passes everything in and I don't want that.

I want something like

<AddStorageItemButton test={()=>this.showAddStorageItemModal(this)} />

then in my the component I tried to do

 <a href="#"onClick={() => this.props.test(true) }> Add</a>

Here is my function.

export function showAddStorageItemModal(show) {
    return function (dispatch) {
        dispatch({ type: actions.SHOW_ADD_STORAGE_ITEM_MODAL, payload: show });
    };
}

Edit here is more of my structure

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

import 'materialize-css/sass/materialize.scss';
import '../styles/main.scss';


import AddStorageItemButton from './AddStorageItemButton.js';

import { showAddStorageItemModal } from '../actions/StorageItemActions.js';

class App extends React.Component {
  render() {
    return (
      <div>
          <AddStorageItemButton {...this.props} test={this.props.showAddStorageItemModal(this)} />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    // reducers
  };
}

function matchDispatchToProps(dispatch) {
  return bindActionCreators({
    showAddStorageItemModal: showAddStorageItemModal,
  }, dispatch);
}


export default connect(mapStateToProps, matchDispatchToProps)(App);

Upvotes: 0

Views: 58

Answers (2)

Praveen Prasad
Praveen Prasad

Reputation: 32107

//I am hoping you have bind showAddStorageItemModal to this in constructor

<AddStorageItemButton test={this.showAddStorageItemModal} />




 <a href="#"onClick={() => this.props.test(true)() }> Add</a>

Upvotes: 0

Rob M.
Rob M.

Reputation: 36511

Since showAddStorageItemModal is returning a closure, I think what you want to do is pass the return value of that function as the prop:

<AddStorageItemButton test={this.showAddStorageItemModal(this)} />

That way when you click, the dispatch will be invoked

Upvotes: 1

Related Questions