Bram z
Bram z

Reputation: 725

React/ES6 -> How to call an React component class method from another component?

Is it possible to call class methods from other (React) components from within a class/component?

Example:

// file x.js
import React, { Component } from 'react'

class X extends Component {
    methodY() {
        console.log('methodY')
    }
    render() {
        return <div />
    }
}

export default X



// file z.js
import React, { Component } from 'react'

class Z extends Component {
    render() {
        return <button onClick={X.methodY} />
    }
}
export default Z

Upvotes: 2

Views: 1235

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44589

It might be possible from a technical point of view - but you really shouldn't.

It's important when starting to use a new framework to embrace the ideology and the patterns of its community. In the case of React, there's no such things as classes and methods. Instead, there's only components and data (and to some extend state).

Following flux principle, you should try to architecture your application in a way that data flows a single way. From the top to the bottom.

As such, instead of component Z calling a function on component X, you can have X receive a function from the parent component modifying the state of that component and then passing a new value to X.

const A = ({onClick}) => (
  <button onClick={onClick}>Click me</button>
);

const B = ({value}) => (
  <span>{value}</span>
);

class Parent extends React.Component {
  constructor() {
    this.state = {
      foo: 'foo'
    };
  }

  render() {
    return (
      <div>
        <A onClick={() => this.setState({foo: 'bar'})}/>
        <B value={this.state.foo}/>
      </div>
    );
  }
}

As you can see, the parent component is now in charge of handling the state and connecting different sibling components together.

As you move further into your exploration of React, you might start to use Redux to extract the logic around data and state completely outside your component. What you'll end up with is presentational components and containers components.

Upvotes: 3

Related Questions