Home > Blockchain >  How to pass function from class parent component to child functional component
How to pass function from class parent component to child functional component

Time:10-08

what I have been trying is this:

The parent component is a class component with a function logToConsole. I summarized the code below:

I am trying to pass Function from parent component to a child functional component Parent Component:

    logToConsole = () => {
      console.log("test);
    }
    render(){
      return(
        <ChildComp logThis={this.logToConsole} />
      )
    }

The ChildComp is:

    const ChildComp = (props) => (
      <button onClick={()=>props.logThis()}>Click Here</button>
    )
    
    export default ChildComp

However I am getting logThis is not a function. How do I solve this issue is there a better way to do this?

CodePudding user response:

Parent:

import React from "react";
import Child from "./Child";

class Parent extends React.Component {
  logToConsole = () => {
    console.log("test");
  };
  render() {
    return <Child log={this.logToConsole} />;
  }
}
export default Parent;

Child:

export default function Child(props) {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={props.log}>Log</button>
    </div>
  );
}

Live Demo

Codesandbox Demo

CodePudding user response:

logToConsole = () => {
  console.log("test);
}

should become

const logToConsole = () => {
    console.log("test");
};

CodePudding user response:

Your code looks fine. What I think is missing is that you need to return the render in the ChildComp

const ChildComp = (props) => (
  return <button onClick={()=>props.logThis()}>Click Here</button>
)

export default ChildComp

I also think you need to setup configurations for class properties if you don't intend to use constuctor function.

Assuming you use constructor function in your class you should be fine all you need to do is this

constructor() {
  this.logToConsole = this.logToConsole.bind(this)
}

However if you are using a class properties use the instructions provided here https://btholt.github.io/complete-intro-to-react-v6/class-properties

CodePudding user response:

Your child component should be <button onClick={props.logThis}>Click Here</button>

  • Related