React-rails: Passing declared javascript functions via react_component?

Created on 19 Feb 2015  路  6Comments  路  Source: reactjs/react-rails

I'm implementing Reflux into my application. I have a component that takes an onSelect function property, is there a way to do something like:

function onSelect(item) {
    CategoryActions.setSelected(item);
}
<%= react_component('Tree', tree: @categories, onSelect: 'onSelect' %>

Does anyone have a solution?

Most helpful comment

if(typeof this.props.onChange === 'string'){
  window[this.props.onChange](name, value)
}else{
  this.props.onChange(name, value)
}

I came with this solution so you can pass the name of the function and if it is pass as a string you go check the window object
Do you think it is a bad idea?

All 6 comments

Depending on where this shared function lives in JavaScript, you could work around this by using a wrapper component.

Given a shared function like this:

// It's not really a good idea to attach random functions to `window`,
// but it's just an example!
window.onCategorySelect = function(item) {
    CategoryActions.setSelected(item)
}

You could create a wrapper which passes that function to a component on the inside:

window.CategoryTree = React.createClass({
  render: function() {
    return (
      <Tree 
        tree={this.props.category} 
        onSelect={window.onCategorySelect}
      />
    )
  }
)

Then, render the wrapper with the Rails helper:

<%= react_component("CategoryTree", tree: @categories) %>

That way:

  • Rails renders the wrapper, CategoryTree
  • CategoryTree renders Tree with the desired event handler

Hope that helps!

That was a solution I came to, but that's going to produce a ton of wrappers, especially for my other components like grids and dropdowns. I might have to ditch the react_component helper to avoid having tons of dumb wrapper components.

@JosephShering If you have a reference for this handler defined you could access it from properties. Say you have a handlers property that stores these function references. You could use

handlers[this.props.selectHandler]

and pass selectHandler from react_component. Any issues with achieving that?

I hope one of these solutions worked for you!

Sorry to dredge up such an old issue, but for the sake of people finding this via google et al., another way to use js in component props is to use a factory-like function in your js.

e.g

window.MyComponentInstance = (args) => <MyComponent onSelect={() => console.log('onSelect')} {...args} />;

Then just load MyComponentInstance as you were.

if(typeof this.props.onChange === 'string'){
  window[this.props.onChange](name, value)
}else{
  this.props.onChange(name, value)
}

I came with this solution so you can pass the name of the function and if it is pass as a string you go check the window object
Do you think it is a bad idea?

Was this page helpful?
0 / 5 - 0 ratings