1

I'm trying to call my "hello" method defined in my React class. My prop on the component is set to read the values from the Students state object, with one of the properties being name "hello". The hello property is init from the john default prop. Whenever the john default prop is set to anything but a property, and I log out the object, it displays correctly. But when I try calling my "hello" method from within the john property, nothing happens (It is supposed to log out the word "hello". My question is, are you allowed to call a method from within React's default property or init state methods ? If so, am I implementing the pattern correctly, if not how can I fix it ?

Side Note: If you're wondering about the library which I am using, it is React-Drag & Drop (for decoupling drag and drop interfaces using React)

Code:

import React from 'react';
var ItemTypes = require('../box1/Constants').ItemTypes;
var DropTarget = require('react-dnd').DropTarget;
var Student = require('../box1/box1');
import update from 'react/lib/update';


require('./box2.css');
require('../../containers/Home/home.css');

var BoxSource = {
  drop: function (props, monitor, component) {  
    const item = monitor.getItem();
    console.log(item);
    const delta = monitor.getDifferenceFromInitialOffset();
    const left = Math.round(item.left + delta.x);
    const top = Math.round(item.top + delta.y);
    const id = item.id;
    component.move(id, left, top);
       }
};

function collect(connect, monitor) {
  return {
    connectDropTarget: connect.dropTarget(),
    didDrop: monitor.didDrop(),
    source: monitor.getSourceClientOffset(),
    item: monitor.getItem(),
    drop: monitor.didDrop(),
    result: monitor.getDropResult()
  };
}

var box2 = React.createClass({

    getInitialState: function() {
    return  { Students: {
        '1': { top: 20, left: 80, hello: this.props.john }

      }
    ,text: 0 };
  },

  getDefaultProps: function() {
    return {
      john: this.hello
    };
  },
  move: function(id,left,top){
     this.setState(update(this.state,{
          Students:{ 
               [id]:{
                    $merge:{
                     left:left,
                     top: top
                    }
                  }
                }
            }));       
  },

  onChange: function(e){ 
      this.setState({ text: e.target.value });
  },

  add: function (e){
   var StudentsNew = { };
   for(var i = 1; i <= this.state.text; i++){
         StudentsNew [i] = { left: 100, top: 100 } ;
   }
   var StudentsCopy = this.state.Students;
   var studentMerge = Object.assign(StudentsCopy,StudentsNew);
   this.setState({ Students: studentMerge })
  },

  reset: function(){

       this.setState({ Students:{ [1]: { top: 20, left: 80 } } });


  },

  hello: function(){

       console.log('hello');


  },




  render:function() {
    const { Students } = this.state;
    var connectDropTarget = this.props.connectDropTarget;
    return connectDropTarget(
      <div id = "box">

            {Object.keys(Students).map(key =>{
                const { left, top, title, hello } = Students[key];
                 return(
                     <div>
                            <Student key = {key} id = {key} left = {left}
                            top = {top} hello = {hello} > </Student>

                            </div>

                         );})}

          <button onClick = {this.add}> Enter Amount of Students </button>
          <button onClick = {this.reset}> Reset </button>
          <input onChange = {this.onChange} type="number" name="quantity" min="1" max="200"/><br/>



      </div>
    );
  }
});

module.exports = DropTarget(ItemTypes.STUDENT, BoxSource, collect)(box2);

1 Answer 1

0

getDefaultProps is invoked before the class is initiated. That's why it gives undefined. Maybe you should refer the hello method as a state in getInitialState

EDIT Example of setting a method as a state :

var example = React.createClass({
getInitialState: function(){
    return {
        methodName : this.hello
    }
},
hello: function(){
    console.log('hello');
},

render: function(){
    console.log(this.state.methodName); // call or pass it to a child
    ...
   }
});
2
  • Thanks a lot for your answer. I did not know that default props is invoked so early on. That could definitely be the issue. As for the other part of your answer, can you give a example of what do you mean ? I'm guessing you mean to set the initial state to the hello method. Is so, I tried this earlier and it also did not work May 2, 2016 at 4:21
  • I added an example in my answer. Let's me know if you have any issue
    – Phi Nguyen
    May 2, 2016 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.