2

How do I get a reference to a component using React with ES6?

I have a Component A

class ComponentA extends React.Component {
    doSomethingInComponentA() {
       //do Something here..
    }
}
render(<ComponentA />, document.getElementById('container'));

And Another Component B where I want to call ComponentA's method

class ComponentB extends React.Component {
    doSomethingInComponentB() {
        ComponentAInstance.doSomethingInComponentA()
    }
}

How do I get a reference to ComponentA? I have tried using

var ComponentAInstance = render (<ComponentA />, 
document.getElementById('container'))
export default ComponentAInstance;

But Since I am using Webpack and ComponentA.jsx is my entry point I get the error

Module not found: Error: a dependency to an entry point is not allowed

Is there any workaround for this?

nils
  • 25,734
  • 5
  • 70
  • 79
Nahush Farkande
  • 5,290
  • 3
  • 25
  • 35

1 Answers1

3

React encourages you to build applications with primarily one way data flows. If <ComponentB /> is a direct child of <ComponentA /> then you can pass data (and functions) to it using props.

function ComponentA() {
  const doSomething = () => console.log('I did something');

  return (
    <ComponentB onClick={doSomething} />
  );
}

function ComponentB(props) {
  return (
    <button onClick={props.onClick}>Example<button>
  );
}

However, if <ComponentB /> is a parent of <ComponentA />, or has no direct connection to it, then you need to introduce a event/state management system to allow the components to communicate.

The most popular pattern for solving this problem is called Flux and the most popular Flux implementation is Redux.

With a library like Redux, your components dispatch actions which modify the state of a central store. Other components in your application can listen for changes in the store and respond accordingly.

In your case, you'd need the doSomethingInComponentB method to dispatch an action that would change the store. <ComponentA /> would need to subscribe to changes and call its doSomethingInComponentA method after the appropriate state was changed.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120