U
U
uzi_no_uzi2019-08-12 17:17:07
JavaScript
uzi_no_uzi, 2019-08-12 17:17:07

How to pass a function that expects arguments to another component?

Made a simple example, am I passing the function to the child component correctly?
For some reason, this does not work in my real project, although I pass it in the following way: parent component => child => another child

import React from 'react';

class Component1 extends React.Component {
  constructor() {
    this.func = (category) => {
      //do something
    }
  }
  
  render() {
    <Component2 onOpen={this.func} />
  }
}


class Component2 extends React.Component {
  constructor() {

  }
  
  render() {
    <div onClick={() => {this.props.onOpen('web')}}> </div>
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2019-08-13
@uzi_no_uzi

We missed passing props to the constructor, calling super(props), the method is declared a little differently, and we missed return in render.
Haven't tested it, but it should be something like this :

import React from 'react';

class Component1 extends React.Component {
    constructor(props) {
        super(props);
        this.func = this.func.bind(this);
    }

    func(name) {
        console.log(`I am ${name}`);
    }

    render() {
        return ( <Component2 onOpen = {this.func}/>)
    }
}


class Component2 extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div onClick={() => {this.props.onOpen('Groot')}}> Who am i ? </div>
        )
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question