bgmaster bgmaster - 2 months ago 22
React JSX Question

How to pass an external method to a stateless functional component in React

I am using FlowRouter/Meteor with React, and am trying to pass a FlowRouter.go method to a react button to navigate to a new page when the button is pressed. I want to do this to keep the button as a reusable component, but am struggling to figure out how to pass the FlowRouter.go method into the stateless functional component. This is a simplified version of what I have right now:

import React, { Component } from 'react';
import { FlowRouter } from 'meteor/kadira:flow-router';

const ParentComponent = () => {
// define text and styles here
return (
<div>
<Button text={text} style={styles} action={FlowRouter.go("Register")}/>
</div>
);
}


and then my button component:

import React, { Component } from 'react';

// Call to action button
const Button = ({text, style, action}) => {
return (
<button className="btn" style={style} onClick={() => action()}>
{text}
</button>
);
}

Button.propTypes = {
text: React.PropTypes.string.isRequired,
style: React.PropTypes.object,
action: React.PropTypes.func
};

Button.defaultProps = {
text: "A button.",
style: {
height: "100%",
width: "100%",
},
action: null
};

export default Button


Does anyone know what syntax is required to load methods from third party libraries into React functional components?

Answer

You need to pass in a function. You are actually executing the FlowRouter.go function by calling FlowRouter.go("Register").

Try this:

const ParentComponent = () => {
  // define text and styles here
  return (
    <div>
      <Button text={text} style={styles} action={() => FlowRouter.go("Register")}/>
   </div>
  );
}

Also... as action is a function you can pass it directly to your onClick, like so:

<button className="btn" style={style} onClick={action}>