Ad

What Are The Best Practices To Get React JS Private Methods?

- 1 answer

When you set a component or element callback for an event, tutorials and documentation show code like this:

'use strict';
import React from 'react';

let FooComponent = React.createClass({
  handleClick(args) {
    ...
  },
  render() {
    return <div>
      <h1>Some title</h1>
      <button onClick={this.handleClick}>Click Me!</button>
    </div>
  }
};
export default FooComponent;

But this handleClick method can be accessed out of this component, if I'd use FooComponent on another component and assign it a reference I can access the handleClick from this other component.

'use strict';
import React from 'react';
import FooComponent from './FooComponent';

let BarComponent = React.createClass(
  handleBarComponentClick(e) {
    this.refs.fooComponent.handleClick(null);
  },
  render() {
    return <div>
      <FooComponent ref="fooComponent" />
      <button onClick={this.handleBarComponentClick}>Other click</button>
    </div>
  }
);
export default BarComponent;

I don't like the fact that I can access that method, which in my opinion should be private or maybe I don't have to worry about it. But to fix that I started using this "good/bad practice" in my projects to avoid that method from being accessed.

'use strict';
import React from 'react';

function handleClick(args) {
  ...
}

let FooComponent = React.createClass({
  render() {
    return <div>
      <h1>Some title</h1>
      <button onClick={handleClick.bind(this)}>Click Me!</button>
    </div>
  }
};
export default FooComponent;

So it cannot be accessed from outside components.

My doubt is, if what I'm doing is a good or bad practice, or what could be the problems that could happen or not if I continue doing this? Or maybe I don't have to worry to set the event handlers inside the createClass argument?

Thanks in advance :)

Ad

Answer

Have you checked the Flux pattern? https://facebook.github.io/react/docs/flux-overview.html

In my React apps, this is not a concern. Although I do not define event handlers in a private way, the general rule is that you NEVER call a method on a component. If the subcomponent needs to notify its parent of something, this is accomplished either by a callback transferred from parent to child as a prop or by mutating a global state (via an action) in the child component. If, on the other hand, is the parent that needs to accomplish something on the child, then it changes the props (or the values of such props) on the subcomponent.

Trying to answer your question, I'd say that what you are doing right now (defining the event handlers in a private scope) is ok. But I think is more of a hassle to do such a thing for every handler. I would suggest you to review if the general architecture of your app is in line with what React suggests.

Ad
source: stackoverflow.com
Ad