React Webpack. Why is there an error when calling a function from a child component?


I hope you can help. I removed the code a lot to make it easier to read.

The parent component passes the function renderHack()

to the component selectBlock

.

The function raises an error: Uncaught TypeError: Cannot read property 'props' of null

Parent component

import React from 'react';
import ReactDOM from 'react-dom';
import SelectBlock from './SelectBlock.js';

export default class SiteFront extends React.Component {

  constructor(){
    super();
    this.state = {
     jsonData : []
    };

  renderHack(){
    console.log("renderHack Fired.");
  };

  render() {
    return (
      <div className="container">
        <div className="inner">

          <SelectBlock
            renderHack={this.renderHack.bind(this)}
          />

        </div>
      </div>
    );
  }
};

      

Child component

import React from 'react';
import ReactDOM from 'react-dom';

function submitHandler(e){
  e.preventDefault();
  this.props.renderHack();
};

export default class SelectBlock extends React.Component {
  render() {
    return (
    <form onSubmit={submitHandler}>
      <input type="submit" value="submit"/>
    </form>
    );
  }
};

      

EDIT: Thanks to @azium. I changed onSubmit={submitHandler}

to onSubmit={submitHandler.bind(this}

and it worked.

I don't know what I am doing wrong. I haven't done React builds in months, so I'm a little rusty. I thought it was correct.

Your help is appreciated. Thank you Mo

+3


source to share


1 answer


Move submitHandler

to your class. It should look like this:

export default class SelectBlock extends React.Component {
  submitHandler(e){
    e.preventDefault();
    this.props.renderHack();
  }

  render() {
    return (
    <form onSubmit={this.submitHandler}>
      <input type="submit" value="submit"/>
    </form>
    );
  }
};

      



The reason you were getting the error was because it this

was equal null

internally submitHandler

, as it should be when the function is not being called on an object .

Usage submitHandler.bind(this)

is an alternative solution, but it looks more hacky than just submitHandler

a method of your component class. In general, if you need access to props in a function called by your component, it must be a method of your component class, so it can be accessed this.props

unnecessarily bind

.

+1


source







All Articles