SiGaban
SiGaban

Reputation: 91

calling javascript method from react

I am trying to call a javascript function from react in the process of adapting a "React" based "Menu" on some old function previously written with jquery

below is my code for the menu

 class Menus extends React.Component{
      constructor(props) {
      super(props);
      this.state = {
      visible: false,
      data: []
    };
  }

  componentDidMount(){
    var _this = this;
    this.setState({data: this.props.data});
  }

  handleClick () {
    var active = !this.state.visible;
    this.setState({ visible: active });
    console.log(this.props.data.MenuText);
  }

  menuTrigger(params){ 
    var func="testalert";//this.props.data.onclick;
    var fnparams = JSON.parse(this.props.data.Parameter);
    // find object
    var fn = eval(func);

    // is object a function?
    console.log('typeof fn === "function":',typeof fn === "function" , typeof fn,fnparams);

            fn.apply(null,fnparams); 
    console.log('Executing:',this.props.data.onclick);
  }
  render(){
    var childNodes;
    var classObj;
    var url;
    childNodes = null;

    if (this.props.data.Children.length) {
      childNodes = this.props.data.Children.map(function(node, index) {
        return  <Menus data={node} />
      });
      classObj = {
        togglable: true,
        "togglable-down": this.state.visible,
        "togglable-up": !this.state.visible
      };
    }

    var style;
    if (!this.state.visible) {
      style = {display: "none"};
    }
    if (childNodes != null){
      return (
        <li>
          <a href="#" onClick={this.handleClick.bind(this)} className="menu {classNames(classObj)}">
            <i className="fa fa-road"></i>
            {this.props.data.MenuText}
          </a>
          <ul style={style} className="treeview-menu">{childNodes}</ul>
        </li>
      );
    }else{
        return (
          <li>
            <a href="#" className="menu" onClick={() => this.menuTrigger(this.props.data.Parameter)}>
                <i className="fa fa-files-o"></i>
               {this.props.data.MenuText}
           </a>
          </li>
        );
    }
  }
}

the javascript function name is stored in a string format in a json object

var example={ 
"MenuText": "example", 
"Parameter": "{'name':'joe'}",
"onclick": "sayhello"
};

the previous code is implement as such

function sayhello(parameter){
   alert('hi '+parameter.name);
}

i have been trying to execute this but getting an undefined on "parameter".

I am in doubt of few matters here.

  1. why is params empty ? the string is accepting it as "function"

    fn.apply(null,fnparams);

  2. is this a rightful way to use react ?

Upvotes: 0

Views: 112

Answers (1)

Kinnza
Kinnza

Reputation: 1301

Why not use:

   var func="testalert";//this.props.data.onclick;
    var fnparams = JSON.parse(this.props.data.Parameter);
    // find object
    eval(func+'('+fnparams+')');

Upvotes: 1

Related Questions