0

I have a class component as a parent and a functional component as a child of the class component. I'm passing a callback function to the child as a prop, but when I call it I get a type error:

"TypeError: this.setState is not a function"

in the function in the parent.

Any ideas on how to solve this?

[EDIT] Code example.

Parent component:

import React, { Component } from 'react';

class NotificationsLayout extends React.Component {
    editConfigCompleted() {
        this.setState({
            templateDataChangedForTasksComponent: true,
            templateDataChangedForTemplatesComponent: true
        })
        this.closeEditConfigModal();
    }

    render() {        
        return (
            <div className="animated fadeIn">
                <RecipientConfigEditor completionAction={this.editConfigCompleted} />
            </div>
        )
    }
}

export default NotificationsLayout;

Child component:

import React, { useState, useEffect, useContext } from 'react';

export default function RecipientConfigEditor(completionAction) {

    function handleButtonClick() {
        completionAction();
    }

    return (
        <button onClick={handleButtonClick}></button>
    )
});
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
user356443
  • 29
  • 7

1 Answers1

1

Either bind in a constructor

import React, { Component } from "react";
import RecipientConfigEditor from '....wherever';

class NotificationsLayout extends Component {
  constructor(props) {
    super(props);
    this.editConfigCompleted = this.editConfigCompleted.bind(this);
  }

  editConfigCompleted() {
    this.setState({
      templateDataChangedForTasksComponent: true,
      templateDataChangedForTemplatesComponent: true
    });
    this.closeEditConfigModal();
  }

  render() {
    return (
      <div className="animated fadeIn">
        <RecipientConfigEditor completionAction={this.editConfigCompleted} />
      </div>
    );
  }
}

export default NotificationsLayout;

or bind when setting callback

import React, { Component } from "react";
import RecipientConfigEditor from '....wherever';

class NotificationsLayout extends Component {
  editConfigCompleted() {
    this.setState({
      templateDataChangedForTasksComponent: true,
      templateDataChangedForTemplatesComponent: true
    });
    this.closeEditConfigModal();
  }

  render() {
    return (
      <div className="animated fadeIn">
        <RecipientConfigEditor completionAction={this.editConfigCompleted.bind(this)} />
      </div>
    );
  }
}

export default NotificationsLayout;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181