SimplyPhy SimplyPhy - 2 months ago 6
Javascript Question

Javascript : How to select elements within one instance of a react class?

I'm trying to select elements (divs with a specific class) within one instance of a React component when a click event is registered from within that same component. I don't want divs with that class to be selected from other instances of this component.

My issue is that, at any given time, there could be any number of instances of this component. Do I have to create a unique ID for each component when it's mounted, or is there some way React lets me reference to only elements found within a specific instance of a component? Can it be done using a callback function within a React class somehow?

For Example:

var MyClass = React.createClass({
makeDivsBigger: function() {
...? // How to only select the divs within the current instance?
},

render: function() {
<div className="container">
<div className="dark"></div>
<div className="light"></div>
<div className="bright"></div>
<button onClick={this.makeDivsBigger}></button>
</div>
}
});

Answer

There's a few ways to go about this, but one thing you rarely want to do is query the DOM to find elements to work on. Those elements are already inside your React universe so you don't need to find them!

A better approach would be to have the parent component control the size of the elements using internal state.

Here's one example implementation:

var MyClass = React.createClass({
  getInitialState: function() {
    return {
      size: ''
    };
  },

  makeDivsBigger: function() {
    this.setState({
      size: 'bigger'
    })
  },

  render: function() {
    <div className="container">
      <div className={"dark " + size}></div>
      <div className="light"></div>
      <div className="bright"></div>
      <button onClick={this.makeDivsBigger}></button>
    </div>
  }
});

// somewhere in your CSS
.bigger {
  height: 500px;
}