dv3
dv3

Reputation: 4579

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 ..

Upvotes: 5

Views: 8453

Answers (3)

Ngọc Bạch Văn
Ngọc Bạch Văn

Reputation: 94

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" />
  }
}

Upvotes: 6

eden
eden

Reputation: 6103

Creating an instance of a class to call a function seems wrong to me. I'm not sure but its like calling a function from different Activity inside another Activity in Android: You can't and mustn't do that.

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. This may change and improve your overall app logic.

Upvotes: 0

Kesem David
Kesem David

Reputation: 2245

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 :)

Upvotes: 1

Related Questions