Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function in props is undefined

When trying to pass a function to a child component, that function is undefined. Actually I can not even execute it directly in my class. Would you think there is a typo?

class FriendsPage extends Component {
  constructor(props){
    super(props);
    this.mylog = this.mylog.bind(this);
  }
  mylog(){
        console.log("test debug");
  }
  renderItem(item) {
      return (<User friend={item} key={item.id} mylog={this.mylog}/>);
  }

class User extends Component {
  constructor(props){
    super(props);
  }
  render() {
      this.props.mylog(); // <== This is undefined
    ...
  }
like image 994
Arkon Avatar asked Nov 08 '22 01:11

Arkon


1 Answers

Works fine. Though if you try to render <User /> without prop named mylog at any other location, it will be undefined.

class FriendsPage extends React.Component {
    constructor(props) {
      super(props);
      this.mylog = this.mylog.bind(this);
    }
    mylog() {
      console.log("test debug");
    }
    render() {
      return ( < User mylog = {
          this.mylog
        }
        />);
      }
    }
    class User extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        this.props.mylog();
        return <h1 > Hello < /h1>;
      }

    }

    ReactDOM.render( < FriendsPage / > , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 133
Pankaj Avatar answered Nov 14 '22 23:11

Pankaj