Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function from different Component?

I have a basic class:

export default class Foo extends Component{
 constructor(props){}
 woop(){
  somethingimportanthappening..
 }
}

in the other component I import it like this:

import Foo from './Foo'
export default class Component2 extends Component{
 constructor(props){}

 randomfunction(){
   Foo.woop() // FAILS
 }
}

How can I call the function "woop" from the other component (Component2)? Foo.woop() isn't working ..

like image 516
dv3 Avatar asked Sep 13 '16 12:09

dv3


People also ask

How do you call a function from another component in react?

Imo, the proper way to call a function of a different class to pass the function callback as props (if there is a parental relation). If there isn't any, triggering Events using react-native-simple-events is fairly simple. Alternatively, you can use Redux which makes your app more robust.

How do I call Ngoninit from another component?

The short answer is to use ViewChild to call the function on component B.


2 Answers

In React a component have an independent function, so in Foo component you define it, something like

export default class Foo extends Component{
  constructor(props){}
  woop(){
    somethingimportanthappening..
  }
  render() {
    <div>Class Foo</div>
  }
}

and when you want to use Foo component, you just import and use

<Foo />

and if you want to use a function in Foo component, you can define a reference to Foo

<Foo ref="foo" />

then use it by

import Foo from './Foo'
export default class Component2 extends Component{
  constructor(props){}

  randomfunction(){
    this.refs.foo.woop();
  }

  render() {
    return <Foo ref="foo" />
  }
}
like image 116
Ngọc Bạch Văn Avatar answered Sep 28 '22 05:09

Ngọc Bạch Văn


Since woop is not a static function you cannot Foo.woop()

You should instantiate a Foo instance as follows:

import Foo from './Foo'

export default class Component2 extends Component{
    private fooInstance: Foo;

    constructor(props){
      this.fooInstance = new Foo(props);
    }

    useFoo(){
      this.fooInstance.woop();
    }
}

Let me know if something is unclear :)

like image 33
Kesem David Avatar answered Sep 28 '22 06:09

Kesem David